Strange behavior using braces in Java

2020-05-25 04:21发布

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.

标签: java braces
9条回答
Animai°情兽
2楼-- · 2020-05-25 04:51
Test(){System.out.println("1");}

    {System.out.println("2");}

    static{System.out.println("3");}

static things are executed first, {System.out.println("2");} isn't a part of a function, because of its scope it is called first, and Test(){System.out.println("1");} is called last because the other two are called first

查看更多
不美不萌又怎样
3楼-- · 2020-05-25 04:51

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.

查看更多
叛逆
4楼-- · 2020-05-25 04:55

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.

查看更多
登录 后发表回答