简体   繁体   English

如果声明是在主方法中进行且在循环内部进行初始化,则在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
    }
}

This gives an error: variable x might not have been initialized System.out.println(x); 这给出了一个错误:变量x可能尚未初始化System.out.println(x); ^ 1 error; ^ 1个错误;

However, below code working fine 但是,下面的代码工作正常

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

Here in both the code, the only difference is that in 1st case, the variable is initialized in "for loop" while in 2nd case it is initialized in "if block". 在这两个代码中,唯一的区别是在第一种情况下,变量在“ for循环”中初始化,而在第二种情况下,变量在“ if块”中初始化。 then why it is making difference. 那为什么会有所作为。 Kindly explain to me as I am not able to find the real reason. 请给我解释一下,因为我找不到真正的原因。

The problem is that the compiler doesn't know that x will be initialized when you access it. 问题在于,编译器在访问x时并不知道x 被初始化。 That's because the compiler doesn't check whether the loop body will actually be executed (there might be rare cases where even such a simple loop might not run). 这是因为编译器不会检查循环主体是否会实际执行(在极少数情况下,即使这样的简单循环也可能无法运行)。

The same would be true for your if-block if the condition wouldn't be always true, ie if you'd use a boolean variable like this: 如果条件并非始终为真,则对于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);

You as a human would say "but cond is initialized to true and will never change" but the compiler doesn't know for sure (eg because of possible threading issues) and thus it will complain. 您作为人类会说“但是cond初始化为true并且永远不会改变”,但是编译器不确定(例如由于可能的线程问题),因此它会抱怨。 If you'd make cond a final variable then the compiler would know that cond would not be allowed to change after initialization and thus the compiler can inline the code to effectively have if(true) again. 如果将cond作为最终变量,则编译器将知道初始化后将不允许cond进行更改,因此编译器可以内联代码以再次有效地具有if(true)

It is accessible still there is a chance that the program will never access the for block. 仍然可以访问程序仍然有可能永远不会访问for块。 Since compiler does not meet any other initialization of the var outside the for loop it gives you an error. 由于编译器在for循环外不满足var的任何其他初始化要求,因此会给您一个错误。 In order to compile it you have to initialize the variable with a default value : 为了进行编译,您必须使用默认值初始化变量:

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

In this code: 在此代码中:

public static void main (String[] args) { 公共静态void主(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 will only be set if the loop runs. x仅在循环运行时设置。 The compiler considers it a possibility that that will never happen. 编译器认为这种可能性永远不会发生。

In the other case: if(true) the compiler recognizes as "This will happen" 在另一种情况下: if(true)编译器识别为“这将发生”

If you want to avoid this, change 如果要避免这种情况,请更改

int x;

to

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

If you change the condition in the if block from true to false you would get the same error that variable 'x' might not have been initialized . 如果将if块中的条件从true更改为false ,则会收到与variable 'x' might not have been initialized相同的错误。 When you do if(true) the compiler can understand that the code inside if block will always run and hence the variable x would always be initialized. 当您执行if(true) ,编译器可以理解if块中的代码将始终运行,因此变量x将始终被初始化。

But when you initialize the variable inside the for loop, it may happen that the for loop is never run and variable is left uninitialized. 但是,当您在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);
        }

To avoid this scenario initialize the variable as int x = 0; 为了避免这种情况,将变量初始化为int x = 0;

在java for运行时评估for循环中,因此编译器忽略对循环内变量初始化的检查,这就是“ x”必须使用值初始化的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM