Which is the right option? C or D?

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?

  • A) c x y g
  • B) c g x y
  • C) x c y g
  • D) x y c g
  • E) y x c g
  • F) y c g x

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow