Practice mode Java

Given class A { int x = 1; { x = 2; } A() { x = 3; } }, what does System.out.println(new A().x); print?

Correct answer C. 3

Explanation

When an object is created, field initialisers and instance initialiser blocks run in textual order after the superclass constructor returns, and the rest of the constructor body runs last. So x becomes 1, then 2, and finally 3. The constructor body always has the last word, which is why 2 is a tempting but wrong choice.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.