Report for order of the execution or initialization of the static block, non-static block and constructor in java.

Bavatharany Mahathevan
3 min readJan 5, 2022

--

In this article, we are going to check the order of the initialization or execution of the static block, non-static block and constructor.

As we know that, static members are executed at class loading time and the non-static block (instance block) and constructor are executed when the new object is created by calling the constructor.

Hence, we are going to check the order of them.

In this StaticDemo01 class, there are

  1. static block
  2. non-static block
  3. static block
  4. constructor.

They are in this order in the class respectively.

But, there is no object instantiated, which means that there is no constructor call with a new keyword. Therefore, The non-static block and constructor are not initialized here.

So,we get the output like:

output

Here, the only static blocks are initialized when running the program.

the static blocks are initialized based on their order in the class.

Let's see another example.

In the above StaticDemo02 class, there are

  1. constructor
  2. non-static block
  3. static block
  4. static block
  5. non-static block

They are in this order in the class respectively.

And, an object also is instantiated, which means that the constructor is called with a new keyword.

output of the StaticDemo02 class

first, The static blocks are initialized in their order

then, non-static blocks are initialized in their order

finally, the constructor

Let's see another example for it.

the StaticDemo03 class is a tricky one, there are

  1. a static block
  2. non-static block
  3. the static block which creates a new instance
  4. static block
  5. constructor

They are in this order in the class respectively.

As per the initialization order, the output is:

In the 2nd static block, we call a new instance: It calls, non-static block then calls constructor internally . Then other static blocks are executed in order.

So, we get the output from

1st stack block: count is 0

then the 2nd static block,

It calls a new instance, as next, the non-static block and constructor are initialized and executed.

  1. in the non-staic block, first, there, the count variable is initialized as 5.
  2. then, the constructor prints the count value as 5
  3. finally, print the statement of the static block. the count is still 5.

After completing the 2nd static block, it comes to the 3rd static block. There is no more static block.

Summary: the order of initialization or execution

1. the static blocks are declared and initialized in the order they appear in the class.

2. the non-static blocks are declared and initialized.

3. the constructor

--

--