Order of Execution of Non-Static Blocks in Java



In this article, we will learn about the order of execution of non-static blocks with respect to a constructor in Java. Whenever an object is created, a non-static block will be executed before the execution of the constructor.

Non-Static Blocks

The Non-static blocks are class-level blocks that do not have a prototype. A non-static block needs to execute any logic whenever an object is created, irrespective of the constructor.

Syntax

The following is the syntax for non-static block initialization:

{
    System.out.println("Non-static block");
}

The Non-static blocks are automatically called by the JVM for every object creation in the Java stack area. We can create any number of Non-static blocks in Java.

Constructor

Java constructors are a special kind of method that is used to initialize an object when it is instantiated. It shares the same name as its class and is syntactically identical to a method. Constructors, however, do not have an explicit return type.

Syntax

The following is the syntax for constructor initialization:

public MyClass() {
    System.out.println("Constructor executed");
}

Order of Execution

The order of execution is as follows in Java when an object of a class is instantiated:

  • Non-Static Blocks Execution: The order of execution of non-static blocks is the order in which they are defined. If there are several non-static blocks, then they are called one by one before any constructor is invoked.
  • Constructor Execution: The appropriate constructor is invoked after all non-static blocks have been executed.
  • Static Blocks Execution: Static blocks are executed only once, when the JVM first loads the class, not during object creation.

Example of Non-Static Blocks

Below is an example to show the order of execution of non-static blocks with respect to a constructor in Java:

public class NonStaticBlockTest {
   {
      System.out.println("First Non-Static Block"); // first non-static block
   }
   {
      System.out.println("Second Non-Static Block"); // second non-static block
   }
   {
      System.out.println("Third Non-Static Block"); // third non-static block
   }
   NonStaticBlockTest() {
      System.out.println("Execution of a Constructor"); // Constructor
   }
   public static void main(String args[]) {
      NonStaticBlockTest nsbt1 = new NonStaticBlockTest();
      NonStaticBlockTest nsbt2 = new NonStaticBlockTest();
   }
}

Output

First Non-Static Block
Second Non-Static Block
Third Non-Static Block
Execution of a Constructor
First Non-Static Block
Second Non-Static Block
Third Non-Static Block
Execution of a Constructor
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-05-07T18:33:34+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements