When I run the following code:
public class Test {
Test(){
System.out.println("1");
}
{
System.out.println("2");
}
static {
System.out.println("3");
}
public static void main(String args[]) {
new Test();
}
}
I expect to get the output in this order:
1
2
3
but what I got is in reverse order:
3
2
1
Can anyone explain why it is output in reverse order?
================
Also, when I create more than one instance of Test
:
new Test();
new Test();
new Test();
new Test();
static block is executed only at first time.
static things are executed first,
{System.out.println("2");}
isn't a part of a function, because of its scope it is called first, andTest(){System.out.println("1");}
is called last because the other two are called firstFirst, class is loaded into the JVM and class initialization happens. During this step static blocks are executed. "{...}" is just a syntactic equivalent of "static{...}". Since there is already a "static{...}" block in the code, "{...}" will be appended to it. That's why you have 3 printed before 2.
Next once the class is loaded, java.exe (which I assumed you executed from the command line) will find and run the main method. The main static method initializes the instance whose constructor is invoked, so you get "1" printed last.
Static blocks are executed first.
And then the instance instance intialization blocks
Please see JLS for instance intializers
{
// sop statement
}
you cannot have a return statment within the instance initialization block, just like constructors.