4

Here is some simple java code .

class Test {
    public static void main(final String[] args) {
        TestClass c = new TestClass();
        System.out.println(c.x);
    }
}

class TestClass {
    {
        x = 2;
    }
    int x = 1;
}

I am getting the answer 1. Why? Is there no constructor used to initialize?

3 Answers 3

6

TestClass is compiled to be equivalent to this:

class TestClass {
    {
        this.x = 2;
    }

    int x;

    {
        this.x = 1;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Not really - it is compiled to have a no args constructor that contains those two lines.
I don't think the code is compiled to this. The initializers are moved to the constructor added by the compiler.
@user3007882 Please remove word compiled, leave equivalent and all is ok :)
5

The order of execution of initializer blocks, and variable initializer is specified in JLS § 12.5:

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

[...]

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. [..]

So, the initializer blocks and variable initializers executed in order in which they appear in the source file. If you move the variable declaration, int x = 1;, before the initializer block, you'll get the result 2.

Technically, your Test class is compiled to the this:

class TestClass {
    int x;

    public TestClass() {
        super();
        x = 2;
        x = 1;
    }
}

For actual bytecode you can run javap -c command.

Comments

1

Because it would be compiled To :

class TestClass {
    int x; 

    TestClass(){
        this.x = 2;
        this.x = 1;
    }
}

Comments

Your Answer

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