I only spend five minutes to find a duplicate in SO.
My question is simple. Does the following code always work?
public class LexicalOrderStatic {
private static Integer a1 = initA1();
private static Integer a2 = initA2();
private static Integer initA2(){
return new Integer(5) / a1;
}
private static Integer initA1(){
return new Integer(5);
}
public Integer getA1(){
return new Integer(a2);
}
public static void main(String[] args) {
LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
System.out.println(lexLuthor.getA1());
}
}
In java can I be sure that a1 is always initialized before a2 ?
Thanks. Dw is ok if it is asked or if it is very simple.
In java can I be sure that a1 is always initialized before a2 ?
Yes, because the specification (section 12.4.2) guarantees it (emphasis mine):
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
Note that constants are initialized earlier than non-constants (step 6 compared with step 9 quoted above).
See more on this question at Stackoverflow