Order of static variable initialization, Java [duplicate]

They are executed in the order that you write them. If the code is:

public class Test {

    static int k = 1;
    static {k = 2;}

    public static void main(String[] args) {
        System.out.println(k);
    }

}

then the output becomes 2.

The order of initialization is: ..the class variable initializers and static initializers of the class…, in textual order, as though they were a single block.

And the values (for your code) are: k = 0 (default), then it’s set to 2, then it’s set back to 1.

You can check that it’s actually set to 2 by running the following code:

private static class Test {

    static {
        System.out.println(Test.k);
        k = 2;
        System.out.println(Test.k);
        }
    static int k = 1;

    public static void main(String[] args) {
        System.out.println(k);
    }
}

Leave a Comment