Using this.var during var's initialization

initialization, java, undefined-behavior

Solution

It is mentioned in passing in the Example 8.3.2.3-1 in section 8.3.2.3. In the text to the example

class Z {
    static int peek() { return j; }
    static int i = peek();
    static int j = 1;
}
class Test {
    public static void main(String[] args) {
        System.out.println(Z.i);
    }
}

the caption says:

... the variable initializer for i uses the class method peek to access the value of the variable j before j has been initialized by its variable initializer, at which point it still has its default value (§4.12.5).

This should map directly to your situation.

Problem

While researching another question, I was surprised to discover that the following Java code compiles without errors: ``` public class Clazz { int var = this.var + 1; } ``` In my JDK6, `var` gets initialized to `1`. Does the above code have well-defined semantics, or is its behaviour undefined? If you say it's well-defined, please quote the relevant parts of the JLS.

Original source

Related problems