Order execution blocks, constructors in Java

In Java, we have two types of blocks: static block and instance block, and can declare many different constructors. What is the order of execution of blocks, constructors in Java? In this tutorial, let’s learn together!

A static block is a block of code that belongs to a particular class and does not belong to an instance of a class. We define it in the static keyword, for example:

An instance block is a block of code, but it does not belong to the class, it belongs to the instance of the class. It is executed every time an instance of the class is initialized. We define it as follows:

And constructor, I do not need to say about it. You should know it, right :D.

So, what is the order of execution of the blocks, constructors? Let’s look at the code below.

Result:

Order execution blocks, constructors in Java

Obviously, as you see, their execution order would look like this:

  • The first is execute the code in the static block.
  • Then will be in the instance block.
  • And the code in the constructor will do after that.

So in the case of inheritance class as the following example, what should be for the order?

Result:

Order execution blocks, constructors in Java

In this case, the order of precedence will be the parent class first and then the subclass. In principle, the static code blocks are still executable first.

In short:

  • Static blocks will be run when the class is loaded into the JVM.
  • Instance block will be run every time new instance of class is initialized.
  • The instance block will run after the super constructor has run and before the current class’s constructor is run.
5/5 - (1 vote)

Add Comment