小编Lev*_*ess的帖子

java中的局部变量

所有代码都是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 …
Run Code Online (Sandbox Code Playgroud)

java if-statement initialization local-variables

0
推荐指数
1
解决办法
897
查看次数