Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering of instance variable initializers

It seems intuitively clear that in Java, instance variable intitializers are executed in the order in which they appear in the class declaration.

This certainly appears to be the case in the JDK I am using. For example, the following:

public class Clazz {
    int x = 42;
    int y = this.z;
    int z = this.x;
    void print() {
        System.out.printf("%d %d %d\n", x, y, z);
    }
    public static void main(String[] args) {
        new Clazz().print();
    }
}

prints 42 0 42 (in other words, y picks up the default value of z).

Is this ordering actually guaranteed? I've been looking through the JLS, and can't find any explicit confirmation.

like image 792
NPE Avatar asked Apr 05 '13 09:04

NPE


1 Answers

Yes, it is.

The se7 JLS covers instance variable initialization order in the 12.5 Execution section:

...
4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.
...

the JLS for Java 5 mentions in the "Classes" section:

The static initializers and class variable initializers are executed in textual order.

like image 150
khachik Avatar answered Sep 18 '22 13:09

khachik