public class StaticTest {
private static StaticTest stObj=new StaticTest();
private static int VAR1=10;
private static final int VAR2=20;
public StaticTest() {
System.out.println("Var1 : "+VAR1);
System.out.println("Var2 : "+VAR2);
}
public static void main(String[] args) {
System.out.println("VAR1 after constrution : "+StaticTest.VAR1);
}
}
Output :
Var1 : 0
Var2 : 20
VAR1 after constrution : 10
Why is this different behavior for VAR1 and VAR2 ?
VAR2cannot be changed one the class has been initialised, whereas any instance of the class can changeVARlater on.The issue here is that you’re referring to the variable before it has been fully initialised.
You’re creating an instance of the class when loading the class itself, before the other static members have been initialised.
Check the Java Language Specifications for more details (Chapter 12).
(Generally, creating an instance of the class during its own construction will lead to problems: you should avoid this.)