java variable scope, variable might not have been initialized

Tags: , ,



I am studying java, I know Java variable scope, such as class level, method level, block level. However, when I try to practice the variable scope, I meet the error in my code. my code is as following:

public class HelloWorld {
    public static void main(String[] args) {
        int c;
        for (int i=0; i <5; i++) {
            System.out.println(i);
            c = 100;
        }
        System.out.println(c);
    }
}

when I run this code, it display the error: the c variable might not have been initialized, but when I change my code to the following:

public class HelloWorld {
    public static void main(String[] args) {
        int c=0;
        for (int i=0; i <5; i++) {
            System.out.println(i);
            c = 100;
        }
        System.out.println(c);
    }
}

The code will print 100.

How should I understand the scope in my code?

Answer

In Java local variables are not initialized with a by default value (unlike, for example field of classes). From the language specification one (§4.12.5) can read the following:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Because it is explicitly set on the Java language specification the compiler will not try to (and should not) infer that the variable c will always be updated inside the loop:

public class HelloWorld {
    public static void main(String[] args) {
        int c;
        for (int i=0; i <5; i++) {
            System.out.println(i);
            c = 100;
        }
        System.out.println(c);
    }
}

The compiler strictly enforces the standard and notifies you about having breaking one of its rules with the error:

"variable c might not have been initialized"

So even though your code can be formally proven to be valid, it is not the compiler job to try to analyze your application’s logic, and neither does the rules of local variable initialization rely on that. The compiler checks if the variable c is initialized according to the local variable initialization rules, and reacts accordingly (e.g., displaying a compilation error for the case of int c;).



Source: stackoverflow