为什么在下面提到的第一种情况下必须初始化 int 值?

Why int value must be initlize in first case mentioned below?

我有两种不同的情况,我在 if 条件下使用了布尔值。为什么我需要在案例 1 中初始化变量 p?

案例 1:

public static void main(String[] args) {
    int p;
    if(Boolean.TRUE){
        p=100;
    }
    System.out.println(p);
}

案例 2:

public static void main(String[] args) {
    int p;
    if(Boolean.TRUE){
        p=100;
    }
    System.out.println(p);
}

编译器抱怨,因为它认为有一条路径可以在 System.out.println 中使用 p,而无需将其分配给任何东西。它看到 if 语句,并决定由于 p 仅在表达式为真时才赋值,而在表达式为假时则不会赋值,因此 p 可能在此之后未赋值。

当然,我们看到这个并认为编译器必须非常愚蠢,因为表达式不可能为假。好吧......为了保持一致并且不存在从一个供应商编写的编译器到另一个供应商编写的编译器的行为有所不同,规则必须具体说明编译器是什么,不允许"figure out" 关于表达。显然规则不允许它弄清楚 Boolean.TRUE 总是正确的。但是,我还没有记住所有关于明确赋值的规则,所以我不知道具体在这种情况下适用什么规则。

更多: @Ravi Jiyani 评论中提到的重复问题很好地解释了我不知道的规则。

来自Oracle的简单回答:

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

虽然 p 总是从 if 语句初始化,但编译器会调查包装器 Boolean 的所有情况。解决方法:

public static void main(String[] args) {
   int p;
   if(Boolean.TRUE){
       p=100;
   } else {
       p= 0; //for example. The compiler will see all the cases are covered
   }
   System.out.println(p);
}//no error

Boolean.TRUE 是包装器对象和单例。这就是它抛出错误的原因,因为它不知道 Boolean.TRUE 后面隐藏着什么。

Therefore the variable p is not guaranteed to be initialized before it prints.

尝试将条件更改为 if(true) 并且编译时不会出现错误,因为 if (true) 编译器可以推断 p 在读取之前已经初始化