-2

I don't fully understand why the answer is such. This is the code given on the example question:

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 "); 
    } 
} 

So the question is what is the output/result. And the answer is: xycg

Can anyone explain why this is so?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254

1 Answers1

3

Static block executes when class is loaded, i.e no instance of object is needed. So in your case:

static 
{ 
   System.out.print("x "); 
} 

will print x first. It always gets executed first, when the class is loaded.

Any block that is not in the constructor (called instance block) will get executed before the constructor (and after the call to super() in case on inheritance) but not before any static blocks, so:

{ 
   System.out.print("y "); 
}

will then print y

When you create an instance of the class Sequence, you invoke it's constructor, so:

Sequence() 
{ 
   System.out.print("c "); 
} 

will print c.

Finally you invoke the method go of an Sequence object:

void go() 
{ 
   System.out.print("g ");
} 

which will print g

Because of all this, the result is: x y c g

MihaiC
  • 1,618
  • 1
  • 10
  • 14