Alex Rivera | Logout

Strange behavior using braces in Java

Asked 2011-11-18T16:41:22.150
40

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.

Edit
Report

2 Answers

5

First, 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.

answered 2011-11-18T16:50:03.757
4

Because the static{} code is run when the class is first initialized within the JVM (i.e. even before main() is called), the instance {} is called when an instance is first initialized, before it's constructed, and then the constructor is called after all that is done.

answered 2011-11-18T16:45:16.440

Your Answer