static blocks, non static blocks and constructor execution order

Hello guys. Here we’ll try to illustrate in which order do static blocks, non static blocks and constructor executes in java.

Any code written inside class with static keyword is called static block. This static block is class level code. So whenever Class Loader loads the class in jvm the static code in that class is executed. So we should be clear that the static block will be executed only once at time of loading of class. It will be executed before any code in the class. If you have any super class which contains static block too, then the static blocks of the super class will be executed first. We know that higher level classes are loaded first.

The code in class with out any keyword are non static block. Non static blocks are also called initializer blocks because non static blocks are executed when object is initialized i.e. when constructor body is executed. But if we have super class, then constructor of super class is executed. Execution of super class constructor is part of object creation  and execution of sub class constructor is part of object initialization. So as the name implies, initializer block execute after super class constructor but before sub class constructor.

Now we can conclude that->

  • First Static block is executed (class loading )
  • Then super class constructor is executed(object creation).
  • Next initializer block will be executed(before object initialization)
  • Then constructor will be executed(object initialization )

Lets have a look at following code Download code here.

Also a super  class.

Here output will be:

Static of supper
static
non static supper
Supper class constructor
nonstatic
constructor
Main method
non static supper
Supper class constructor
nonstatic
constructor

output

 

Lets summarize Static blocks, Non static blocks and Constructor order of execution again.

  1. Static of super class
  2. Static of class
  3. While creating object each time
    • Super class non static block
    • Super class constructor
    • class non static block
    • class constructor

Log Raj Bhatt

A Computer Science Student and Java Developer.

Leave a Reply

Your email address will not be published. Required fields are marked *

Inline
Inline