9

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.

2
  • 3
    at the time y is assigned, z is still not initialized, therefore it shows 0. Commented Apr 5, 2013 at 9:56
  • 3
    @ShivanRaptor: That's exactly my intuition. The question is whether this is formally specified by the JLS. Commented Apr 5, 2013 at 10:04

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

yes the variables initialisation in the class are executed in the same order. So in your second line y takes the default value o of z since z is not initialised

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.