简体   繁体   中英

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); ^ 1 error;

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". 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. 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:

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

It is accessible still there is a chance that the program will never access the for block. Since compiler does not meet any other initialization of the var outside the for loop it gives you an error. 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) {

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

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.

 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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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