1

I can not figure out why this code:

class HelloWorld
{
    HelloWorld()
    {
        System.out.println("1 cnstr ");
    }

    public static void main(String[] args)
    {
        HelloWorld a = new HelloWorld();
    }


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

gives me the output:

2 cnstr
1 cnstr

Why does line System.out.println("2 cnstr "); work? What kind of block is it? I used jdb and found that JVM starts block with this line in HelloWorld() constructor before any line in it.

Thanks for your help.

alexvassel
  • 10,600
  • 2
  • 29
  • 31

2 Answers2

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

Its an Instance Initialization block. It is run before constructor of the class is executed.

From Documentation:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
PermGenError
  • 45,977
  • 8
  • 87
  • 106
5

It's an instance initializer block, which gets executed before each constructor.

assylias
  • 321,522
  • 82
  • 660
  • 783