How does the static modifier affect this code?

In Java two phases take place: 1. Identification, 2. Execution

  1. 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

  2. The second phase, execution, starts from top to bottom. In Java, the execution starts from the first static members.
    Here your first static variable is static A obj = new A();, so first it will create the object of that variable and call the constructor, hence the value of num1 and num2 becomes 1.
    And then, again, static int num2=0; will be executed, which makes num2 = 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)