Hello Friends what is the use of having just a block in Java class
public class StaticExample {
{
System.out.println("I m here...");
}
}
Hello Friends what is the use of having just a block in Java class
public class StaticExample {
{
System.out.println("I m here...");
}
}
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.
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