java中的局部变量

Lev*_*ess 0 java if-statement initialization local-variables

所有代码都是Java.

public class TestLocal 
{
    public static void main(String [] args) 
    {
        int x;
         if (args[0] != null) 
         { // assume you know this will
           // always be true
             x = 7;  // statement will run
         }
     int y = x; // the compiler will choke here
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是为什么编译器会在这里窒息?它是否绕过if语句(这看起来非常可怕......)如果我在if语句块之外初始化x,那么编译器不会抱怨,如下代码所示:

public class TestLocal 
{
    public static void main(String [] args) 
    {
        int x;
        x = 7; // compiler is happy now..:)
        if (args[0] != null) 
        { // assume you know this will
         // always be true
         // statement will run
        }
        int y = x; // the compiler not complain here now.
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器出现这种可怕的行为?

Rap*_*Cpp 5

Java要求您初始化局部变量作为安全措施.它会阻止你意外地读取奇数值.如果编译器没有抱怨并且你要读取x的值,它可能是任何东西.

  • 编译器无法知道if语句总是如此.如果不是,则x仍未初始化. (3认同)