java - 为什么 if(Boolean.TRUE) {...} 和 if(true) {...} 在 Java 中的工作方式不同

标签 java boolean

我想知道 if 子句中的 Boolean.TRUEtrue 值之间的区别。当我使用 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 expressionBoolean.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/

相关文章:

java - 由于 appiumDriver,无法运行 appium 测试

c++ - 我正在尝试从类中的 boolean 值返回一个字符串,该字符串一直返回 true

java - 调整返回 true/false 的方法

c++ - 无论如何在 C++ 中将 2 维数组煮沸为整数?

java - 在 eclipse 中运行 ant build 导致 cpu 达到峰值并保持在 50%

Java Swing FocusTraversalPolicy 问题

java - 尝试 WSO2 IoT 3.3.0 android 注册时如何修复错误 "Enrollment failed"?

C++ 警告 C4800 - 'int' 强制值为 bool 'true' 或 'false' with switch 语句

java - java中一个if语句中的多个逻辑表达式

java - Java 中具有可能空值的 CharSequence 和 String 对象之间的相等性检查