-1

Hello Friends what is the use of having just a block in Java class

public class StaticExample {
  {
    System.out.println("I m here...");
  }
}
Jayram Rout
  • 57
  • 1
  • 2
  • 8

2 Answers2

7

That's an initialization block. It gets executed when a new instance is created. If you think that that's a job for the constructor, it is a place where you can put code that is executed no matter which constructor is used. They are executed in the order they appear, before the constructor. If you put static in front of an initialization block, it becomes a static initialization block, which is executed as soon as the class is loaded.

tbodt
  • 16,609
  • 6
  • 58
  • 83
  • 2
    Technically they're executed after the super constructor call and before the rest of the body. This is actually important if the superclass ctor calls a virtual method. – Antimony Aug 16 '13 at 02:18
6

It's called an initializer block and is invoked every time an instance of the class is created.

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

The code is invoked before the code in the constructor and doesnt depend on the latter.

public class InitializerExample {

    public InitializerExample() {
        System.out.println("InitializerExample");
    }

    {
        System.out.println("I'm here...");
    }

    public static void main(String[] args) {
        new InitializerExample();
    }
}

will produce

I'm here...
InitializerExample

It is documented in the official tutorial here

Reimeus
  • 158,255
  • 15
  • 216
  • 276