Java Static Initialization vs. Instance Initialization – When to use which?

Static Initialization

Typically static initialization block is used to initialize static variables of a class. The block is called at the time of class initialization. It is called only once. You can initialize static variables inline. If more complicated logic is required for initialization, a static initialization block can be used. The static initialization blocks are called in the order in which they occur, and they are called before the constructors.

For example:

class StaticTest {
static int i;
static {
System.out.println("Static Initialization block is called");
i = 10;
}
StaticTest() {
System.out.println("Static Test Constructor is called");
}
}
class Main {
public static void main (String args[]){
System.out.println(StaticTest.i);
}
}

The output of the above code is as shown below.

Static Initialization block is called
10

view raw
op1.txt
hosted with ❤ by GitHub

Instance Initialization

Instance Initialization or Initializer Block is called whenever an instance of the class is created.
It can be used to execute code that is common to all constructors. This block is executed before the constructor is executed.

For example:

class InitializerTest {
int i;
{
System.out.println("Instance Initialization block is called");
i = 5;
}
InitializerTest() {
System.out.println("Initializer Test Default Constructor is called");
}
InitializerTest(int x) {
System.out.println("Initializer Test Parametrized Constructor is called");
}
}
class Main {
public static void main (String args[]){
InitializerTest obj1 = new InitializerTest();
InitializerTest obj2 = new InitializerTest(10);;
System.out.println(InitializerTest.i);
}
}

The output of the above code is as shown below.
https://gist.github.com/anjanashankar9/2fe14b20263d64dea31719784be57d85.

Ref: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s