为什么如果(Boolean.TRUE){...}如果(真){...}在Java中工作方式不同 [英] Why does if(Boolean.TRUE) {...} and if(true) {...} work differently in Java
问题描述
我想知道的区别 Boolean.TRUE
和内的真实
值如果
条款。为什么它给我一个编译错误(该值可能没有被初始化)当我使用 Boolean.TRUE
而不是真正
。
下面是我的code:
公共类的测试{ 公共无效方法1(){
INT X;
如果(Boolean.TRUE){
X = 200;
}
的System.out.println(×+ X); //编译错误
} 公共无效方法2(){
INT X;
如果属实) {
X = 200;
}
的System.out.println(×+ X); //编译正常
}
}
简短的回答
对于如果(真实)
编译器可以推断出 X
已在读取之前初始化。这并不持有的如果(Boolean.TRUE)
情况。
正式的答案:
所有的局部变量必须具有的明确赋值的读取之前(的 14.4.2局部变量声明的执行):
[...]如果一个声明符没有初始化前pression,,然后每到变量引用必须是转让的执行pceded到变量 $ P $,或通过§16规则发生编译时错误。
块引用>在这种情况下,有参与code preceding的参考变量的
如果
语句,所以编译器执行一些流量分析。然而,在第16章明确赋值:
除了条件布尔运算符的特殊处理
&放大器;&安培;
,||
和?
和布尔值常量前pressions ,前pressions的值不会在流分析考虑。
块引用>所以,因为
真正
是一个布尔值的恒恩pression 和Boolean.TRUE
(这是一个值的引用在堆上,主题自动拆箱等)不的它遵循这如果(真){
X = 200;
}得到
的X
一个明确赋值,而如果(Boolean.TRUE){
X = 200;
}不
I want to know the difference between
Boolean.TRUE
andtrue
values inside anif
clause. Why does it give me a compilation error (that a value may not have been initialized) when I useBoolean.TRUE
instead oftrue
.Below is my code :
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 } }
解决方案Short answer
Forif (true)
the compiler can deduce thatx
has been initialized before it's being read. This does not hold for theif (Boolean.TRUE)
case.Formal answer:
All local variables must have a definite assignment before being read (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.
In this case there's an
if
statement involved in the code preceding the reference to the variable, so the compiler performs some flow analysis. However, as spelled out in 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.So since
true
is a boolean-valued constant expression andBoolean.TRUE
(which is a reference to a value on the heap, subject to auto-unboxing etc) is not it follows thatif (true) { x = 200; }
yields a definite assignment of
x
whileif (Boolean.TRUE) { x = 200; }
does not.
这篇关于为什么如果(Boolean.TRUE){...}如果(真){...}在Java中工作方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!