public class Sequence {
Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}
What is the result?
This is Oracle certification question and answer is option D.I did not understand the answer.I thought option C is correct.Can anyone explain why the answer is option D and not option C?
Basically, it's just a matter of reading through JLS 12.5 (Creation of New Class Instances) carefully.
In particular, note the order of:
Execute the instance initializers and instance variable initializers for this class [...]
Execute the rest of the body of this constructor. [ ... ]
y
is printed by the instance initializer; c
is printed by the body of the constructor - therefore y
is printed first.
See more on this question at Stackoverflow