如果在主方法中声明并在循环内初始化,则在 Java 中不可能从 For 循环外部访问时变量?

Is variable when accessed from outside the For loop is not possible in Java if declaration is done in main method & initialization inside loop?

class Myclass {
    public static void main(String[] args) {

        int x; // Declared in main method

        if (true) {
            for (int i = 0; i < 5; i++) {
                x = 5;// initialized inside loop
            }
        }

        System.out.println(x);// accessing outside for loop
    }
}

这给出了一个错误:变量 x 可能尚未初始化 System.out.println(x); ^ 1 个错误;

但是,下面的代码工作正常

class Myclass {
    public static void main(String[] args) {

        int x; // Declared in main method

        if (true) {
            x = 5;// initialized in if block
            for (int i = 0; i < 5; i++) {
                // x=5;
            }
        }

        System.out.println(x);// accessing outside if loop
    }
}

在这两个代码中,唯一的区别是在第一种情况下,变量在 "for loop" 中初始化,而在第二种情况下,它在 "if block" 中初始化。那么为什么它会有所作为。请向我解释,因为我无法找到真正的原因。

它是可以访问的,但程序有可能永远不会访问 for 块。由于编译器不满足 for 循环之外的 var 的任何其他初始化,因此它会给您一个错误。为了编译它,您必须使用默认值初始化变量:

class Myclass {
    public static void main (String[] args) {

        int x = 0; // Declared in main method and init with a default value.

        if(true) {
            for(int i=0;i<5;i++) {
                x=5;// Reinitialized inside loop
            }
        }
        System.out.println(x); // No problems here.
    }
}

在此代码中:

public static void main (String[] args) {

     int x; // Declared in main method

    if(true)
    {
    for(int i=0;i<5;i++)
       {
           x=5;// initialized inside loop


       }

    }
    System.out.println(x);//accessing outside for loop
}

x 只会在循环运行时设置。编译器认为这有可能永远不会发生。

另一种情况:if(true) 编译器识别为 "This will happen"

如果您想避免这种情况,请更改

int x;

int x = 0; // or use another default variable

问题是编译器不知道x 会在你访问它的时候被初始化。那是因为编译器不检查循环体是否真的会被执行(在极少数情况下,即使是这样一个简单的循环也可能不会 运行)。

如果条件不总是为真,那么对于您的 if 块也是如此,即如果您使用这样的布尔变量:

int x;

boolean cond = true;
if( cond ) {
  x = 5;
}

//The compiler will complain here as well, as it is not guaranteed that "x = 5" will run
System.out.println(x);

你作为一个人会说 "but cond is initialized to true and will never change" 但编译器不确定(例如,由于可能的线程问题),因此它会抱怨。如果您将 cond 设置为最终变量,那么编译器会知道 cond 在初始化后不允许更改,因此编译器可以内联代码以有效地再次拥有 if(true)

如果您将 if 块中的条件从 true 更改为 false,您将得到与 variable 'x' might not have been initialized 相同的错误。当您执行 if(true) 时,编译器可以理解 if 块中的代码将始终 运行,因此变量 x 将始终被初始化。

但是当你在for循环中初始化变量时,可能会发生for循环永远不会运行并且变量未初始化的情况。

 public static void main(String[] args) {

      int x; // Declared in main method
         if(false)
            {
                x=5; //compile error
                for(int i=0;i<5;i++)
                {
                    //x=5 initialized inside loop
                }

            }
            System.out.println(x);
        }

为避免这种情况,将变量初始化为 int x = 0;

在 java for 循环中,在 运行 时计算,因此编译器忽略循环内变量初始化的检查,这就是 "x" 必须用值初始化的原因.