javavariablesscope

Why is there no compilation error on the line above the indicated line?


I'm reading up on Java and I am scratching my head as to why System.out.println("a: " + a); does not yield a compilation error. Where is a ever initialized?

public class localVariableEx {
    public static int a;
    public static void main(String[] args) {
        int b;
        System.out.println("a: " + a);
        System.out.println("b: " + b);  //Compilation error
    }
}

Solution

  • The relevant rules of this are described in the JLS § 4.12.5 Initial Values of Variables (emphasis mine):

    • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10): [...]
    • [...]
    • 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 by the compiler using the rules for definite assignment (§16).

    So while instance variables (such as a) automatically get a default value, local variables (such as b) don't get one and must not be used unless the compiler can verify that a value has been assigned to them.