Why does if(Boolean.TRUE) {…} and if(true) {…} work differently in Java

前端 未结 3 726
小蘑菇
小蘑菇 2020-12-19 00:08

I want to know the difference between Boolean.TRUE and true values inside an if clause. Why does it give me a compilation error (that

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 00:57

    Short answer
    For if (true) the compiler can deduce that x has been initialized before it's being read. This does not hold for the if (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 and Boolean.TRUE (which is a reference to a value on the heap, subject to auto-unboxing etc) is not it follows that

    if (true) {
        x = 200;
    }
    

    yields a definite assignment of x while

    if (Boolean.TRUE) {
        x = 200;
    }
    

    does not.

提交回复
热议问题