Recently I was checking a code online and found the output of the following code :
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 ");
}
}
as:
x y c g
Can anyone please help me to know about the functionality of this code.
Can anyone please help me to know about the functionality of this code.
Sure. The very first thing that happens is that the class is initialized as per section 12.4.2 of the JLS. This involves running the static initializers of the class, as per section 8.7. Here we have a static initializer which prints x
.
The main
method then creates an instance of Sequence
. This follows section 12.5 of the JLS. First the superclass constructor (Object
here) is called, then the instance initializers (section 8.6) then the constructor body. Here you have an instance initializer which prints y
, and a constructor body which prints c
.
Finally, the go
method is executed which prints g
.
See more on this question at Stackoverflow