3

I want to know that does default initialization of static variables happens before static initialization or along with it ?

Let us look at code below:

class Test {

    static {
        System.out.println(Test.a);  // prints 0
        a = 99; // a get 99
        System.out.println(Test.a); // prints 99
    }

    static int a = 10;

    static {
        System.out.println(a); // prints 10
    }

    public static void main(String[] args) {

    }
}

My guess is that when class is loaded , all the static variables are created in memory and default values given to them then and there only. Then static initialization takes place in the order static initializers and static fields that appear in code . Am I right ?

EDIT : I am aware of the order of static initialization but I am unable to get the point in JLS where it tells us that default initialization happens before static initialization takes place ?

2

1 Answer 1

3

You are right.

Static fields and initializers are indeed executed in their declared order :

12.4.2. Detailed Initialization Procedure

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.

And at runtime each class variable is indeed initialized with a default value :

4.12.5. Initial Values of Variables

...

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

For type byte, the default value is zero, that is, the value of (byte)0.

For type short, the default value is zero, that is, the value of (short)0.

For type int, the default value is zero, that is, 0. ...

That's why the actual behavior :

static {
    System.out.println(Test.a);  // prints 0 -> default value for `int`
    a = 99; // a get 99
    System.out.println(Test.a); // prints 99 -> value after previous statement executed
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am aware of the order of static initialization but I am unable to get the point in JLS where it tells us that default initialization happens before static initialization takes place ?
This part implied that : "Each class variable ... is initialized with a default value when it is created"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.