-1

So I have this piece of code, the output produced is xycg... but how? Can someone explain in how that is.

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

I don't even understand how one can write

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

Could this also be explained as well please.

Also The bit where system.out.print("y") is written, how can that be written in it's own block, it's not in the sequence constructor?

RamanSB
  • 1,162
  • 9
  • 26
  • 2
    What don't you try executing yourself, and as per the results try to Google and learn about sequence of call like - static initialization, instance initialization, constructor call etc. – hagrawal7777 Jun 29 '15 at 20:02
  • @hagrawal Could you refer me to a particular link? – RamanSB Jun 29 '15 at 20:05
  • https://www.google.ca/search?q=java+initialization+block+vs+constructor&ie=utf-8&oe=utf-8&gws_rd=cr&ei=c6WRVd7pBIKjyASppLDoCA – hagrawal7777 Jun 29 '15 at 20:07
  • http://www.programcreek.com/2011/10/java-class-instance-initializers/ – BoDidely Jun 29 '15 at 20:12
  • Thanks, It seems my question is a duplicate; there is no need to edit it. Should I just delete it? – RamanSB Jun 29 '15 at 20:47

1 Answers1

1

Static blocks are executed when the class is first loaded.

Non-static initialize blocks are executed before constructors.

Constructors are executed before you can invoke non-static methods on an instance.

It's actually quite a good minimal example of code to demonstrate this order.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • So the {System.out.print("y")} is a non static block which is initialized, after the static block is initialized, hence yielding xy, then the non static method is executed last, thus outputting g at the end so xycg – RamanSB Jun 29 '15 at 20:07