开发者

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 cla开发者_开发百科ss 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
    }
}


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.


b is a variable defined in the method scope only, so the compiler can know that no one initialized it before, but a is a public variable that might be initialized somewhere else.


a is of a primitive type int which will get initialized immediately, which means:

Static class members: get init'ed when the class is loaded (most of the time, when the before main(), but it depends on when the class is loaded).

class S {
  static int a;
}

Non-Static class members: get init'ed when the object is. (most of the time after new, but there're other, more advanced, methods to new an object).

class S {
  int a;
}

Local variables: should be init'ed in the method's scope before first use.

class S {
  void foo() {
    int b = 0;
  }
}

edited after being corrected...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜