我想知道 if
子句中的 Boolean.TRUE
和 true
值之间的区别。当我使用 Boolean.TRUE
而不是 true
时,为什么会出现编译错误(值可能尚未初始化)。
下面是我的代码:
public class Test {
public void method1() {
int x;
if(Boolean.TRUE) {
x = 200;
}
System.out.println("x: " + x); // Compilation error
}
public void method2() {
int x;
if(true) {
x = 200;
}
System.out.println("x: " + x); // Compiles fine
}
}
最佳答案
简答
对于 if (true)
,编译器可以推断出 x
在被读取之前已经被初始化。这不适用于 if (Boolean.TRUE)
情况。
正式回答:
所有局部变量在被读取之前必须有一个明确的赋值(14.4.2. Execution of Local Variable Declarations):
[...] If a declarator does not have an initialization expression, then every reference to the variable must be preceded by execution of an assignment to the variable, or a compile-time error occurs by the rules of §16.
在这种情况下,引用变量之前的代码中包含一个 if
语句,因此编译器会执行一些流分析。然而,如 Chapter 16. Definite Assignment 中所述:
Except for the special treatment of the conditional boolean operators
&&
,||
, and? :
and of boolean-valued constant expressions, the values of expressions are not taken into account in the flow analysis.
所以因为 true
是一个 boolean 值 constant expression和 Boolean.TRUE
(这是对堆上值的引用,受自动拆箱等影响)is not由此可见
if (true) {
x = 200;
}
产生 x
的明确赋值而
if (Boolean.TRUE) {
x = 200;
}
没有。
关于java - 为什么 if(Boolean.TRUE) {...} 和 if(true) {...} 在 Java 中的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28546321/