In Java two phases take place: 1. Identification, 2. Execution
-
In identification phase all static variables are detected and initialized with default values.
So now the values are:
A obj=null
num1=0
num2=0 -
The second phase, execution, starts from top to bottom. In Java, the execution starts from the first static members.
Here your first static variable isstatic A obj = new A();, so first it will create the object of that variable and call the constructor, hence the value ofnum1andnum2becomes1.
And then, again,static int num2=0;will be executed, which makesnum2 = 0;.
Now, suppose your constructor is like this:
private A(){
num1++;
num2++;
System.out.println(obj.toString());
}
This will throw a NullPointerException as obj still has not got a reference of class A.