为什么 if(Boolean.TRUE) {...} 和 if(true) {...} 在 Java 中的工作方式不同 [英] Why does if(Boolean.TRUE) {...} and if(true) {...} work differently in Java

查看:40
本文介绍了为什么 if(Boolean.TRUE) {...} 和 if(true) {...} 在 Java 中的工作方式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 if 子句中 Boolean.TRUEtrue 值之间的区别.当我使用 Boolean.TRUE 而不是 true 时,为什么它会给我一个编译错误(可能尚未初始化一个值).

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 a value may not have been initialized) when I use Boolean.TRUE instead of 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) 情况.

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.

正式回答:
所有局部变量在被读取之前必须有一个明确的赋值 (14.4.2. 局部变量声明的执行):

[...] 如果声明器没有初始化表达式,那么每次对变量的引用都必须在执行对变量的赋值之前,否则会发生编译时错误根据第 16 条的规则.

[...] 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 语句,因此编译器会执行一些流分析.但是,正如 第 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.

所以由于 true 是布尔值 常量表达式Boolean.TRUE (这是对堆上的值的引用,受自动拆箱等影响)不是它遵循

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;
}

产生x的明确赋值,而

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

没有.

这篇关于为什么 if(Boolean.TRUE) {...} 和 if(true) {...} 在 Java 中的工作方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆