Instance Block in Java | Types, Example

In this tutorial, we will learn about the instance initialization block (IIB) in Java with the help of examples. Before understanding it, let us first understand what a block is in Java.

A block in Java is a set of code enclosed within curly braces { } within any class, method, or constructor. A block begins with an opening brace ({) and ends with a closing brace (}).

Between the opening and closing braces, we can write code, which may be a group of one or more statements. The syntax for a set of code written in a block of a class is:

public class Student 
{  // Class block starts.
   // class body
}  // Class block ends.

In Java, every class has a class body enclosed within curly braces, which contains fields, methods, constructors, nested classes, initialization blocks, and other members.

Similarly, every method has a method body enclosed within curly braces that contains a group of statements to perform a specific task. An example of class block and method block is shown in the below figure.

An example of a nested block in Java: method block inside class block.

Types of Blocks in Java


We can broadly classify Java blocks into the following types:

  1. Local block
  2. Instance initialization block (Non-static initialization block)
  3. Static initialization block

Three types of blocks in Java: local, instance, and static blocks.

Local Block in Java


A block defined inside a method, constructor, or another block is called a local block or inner block in Java. This type of block executes whenever the flow of control reaches that block during the execution of the enclosing method, constructor, or block.

Unlike instance initialization blocks, local blocks are mainly used to limit the scope of variables and organize code. We cannot declare a local block with the static keyword.

We can declare a local block inside a method, constructor, or another block. When you place a block inside another block, it is called a nested block in Java. Nested blocks are commonly used in methods, loops, conditional statements, constructors, and initialization blocks.

Example 1: Method with Local Block

public void methodwithInnerblock()
{   // Outer block starts here with opening braces.
    int x = 20;
    System.out.println(" Outer block");
    // Inner (local) block starts here with next opening braces.
    { 
        int y = 30;
        System.out.println("Inner block");
    } // Inner block ends here.
} // Outer block ends here.

A block can exist entirely within another block or entirely outside and separate from another block, but blocks can never partially overlap.

In the above example, a method contains two blocks. The first opening brace and the last closing brace pair define the outer block whereas, the second opening brace and first closing brace pairs define inner or local block. Thus, we can nest a block statement inside another block statement.

Scope of Variables in Local Block


Variables declared inside a method, constructor, or local block are local variables. They can be accessed only within that block in which they are declared and in any nested blocks inside it. In simple words, we can access the local variables only within the block. We cannot access them from outside the block.

Example 2: Accessing Local Variable from Outside Block

public void add() 
{
  int a = 30;
  int b = 40;
  int x = a + b;
} 
System.out.println(x); // compile time error.

In this example, variable x is declared inside the method block. Therefore, we cannot access it outside that block.

Variable Redeclaration in Nested Blocks


A variable declared in an outer block cannot be redeclared in an inner block with the same name. This is because the variable declared in the outer block remains visible within the inner block. Redeclaring it would create ambiguity, so Java reports a compile-time error.

The following example snippet of code will not compile:

public static void invalidRedeclarationMethod()
{    
   int num = 20;
   {
     int num = 30; // Compile-time error.
     int num1 = 40; // Valid
   }  
}

Why does this cause an error?

The variable num declared in the outer block is already in scope within the inner block. Therefore, Java does not allow another local variable named num to be declared inside the inner block.

Instance Initialization Block (Non-Static Block) in Java


An instance initialization block (IIB) in Java is a block of code that is executed whenever an object of a class is created. This block is also known as a non-static initialization block in Java. The general syntax to declare an instance initialization block in Java:

{  
 // Initialization code
}

We usually use an instance initialization block to perform common initialization tasks that need to be executed before the constructor body, regardless of which constructor is called. However, we can also use an instance initialization block to initialize instance variables.

Important Note:

  • An instance initialization block executes before the constructor body only when an instance of the class is created.
  • If a class contains both static initialization blocks and instance initialization blocks, the static initialization blocks execute once when the class is loaded in the memory, whereas the instance initialization blocks execute every time an object is created.
  • We can access both instance variables and static variables inside an instance initialization block.

Example 3: Instance Block with Constructor

Let’s take a simple example program where we will declare an instance initialization block and constructor inside a class Test.

public class Test 
{ 
   // Declare a constructor. 
   Test() 
   { 
      System.out.println("0-arg Constructor"); 
   } 
   // Declare an instance block. 
   { 
      System.out.println("Instance Block"); 
   } 
   public static void main(String[] args) 
  { 
  // Create the object of the class. 
  // This is a named object because it contains reference variable.
     Test t = new Test();

  // This is a nameless object. It is frequently used to reduce the length of the code. 
     new Test(); 
  } 
}

Output:

Instance Block
0-arg Constructor
Instance Block
0-arg Constructor

Which Executes First: Instance Initialization Block or Constructor?


During object creation, instance variables are first assigned their default values. Then, instance variable initializers and instance initialization blocks execute in the order they appear in the class. After that, the constructor body executes. Therefore, an instance initialization block always executes before the constructor body of its own class.

Important Note About Inheritance

When inheritance is involved, the execution order is:

  • Memory is allocated for the object.
  • Instance variables are assigned with their default values.
  • Superclass instance variable initializers and instance initialization blocks execute.
  • The superclass constructor executes.
  • Subclass instance variable initializers and instance initialization blocks execute.
  • The subclass constructor executes.

Use of Instance Initialization Block in Java with Example


Example 4: Use of Instance Block in Java

Let us understand the use and need of Instance Initialization Block (IIB) in Java with the help of an example.

public class Simple 
{ 
// Declare 0-arg constructor. 
   Simple() 
   { 
      System.out.println("0-arg constructor"); 
   } 
// Declare 1-arg constructor with a parameter x of type int. 
   Simple(int x)
   { 
     System.out.println("1-arg constructor"); 
   } 
// Declare 2-arg constructor with parameters x and y of type int. 
   Simple(int x, int y)
   { 
      System.out.println("2-arg constructor"); 
   } 
// Declare an instance block. 
   { 
     System.out.println("IIB"); 
   } 
   public static void main(String[] args) 
   { 
      new Simple(); 
      new Simple(20); 
      new Simple(10,20); 
  } 
}

Output:

IIB 
0-arg constructor 

IIB 
1-arg constructor 

IIB 
2-arg constructor

In this example:

  • During the first object creation, instance block executes first.
  • Once the execution process of instance block is completed, the 0-arg constructor executes.
  • During the second object creation, the instance block executes again, and later 1-arg constructor executes.
  • Similarly, for third object creation, IIB executes first and then 2-argument constructor executes.

Now you can observe that the instance block executes every object creation before the execution of constructor. The constructor logic is specific to the particular objects, but instance block logic remains common for all objects. The main purpose of an IIB is to avoid duplication of common initialization code across multiple constructors.

Order of Execution of Instance Blocks in Java


In Java, we can declare multiple Instance Initialization Blocks (IIBs) inside a class. If multiple instance blocks are present, they are executed in the same order in which they appear in the class, that is, from top to bottom.

Let us understand the order of execution of instance blocks in Java with an example.

Example 5: Order of Execution of Instance Blocks

public class MultipleIIB 
{ 
  MultipleIIB()
  { 
     System.out.println("0-arg constructor"); 
  } 
  MultipleIIB(int x)
  { 
     System.out.println("1-arg constructor"); 
  } 
  { 
     System.out.println(" First IIB"); 
  } 
  { 
     System.out.println("Second IIB"); 
  } 
public static void main(String[] args) 
{ 
   new MultipleIIB(); 
   new MultipleIIB(5); 
 } 
}

Output:

First IIB 
Second IIB 
0-arg constructor 
First IIB 
Second IIB 
1-arg constructor

Q. How many times instance block will be executed in the below Java program?

public class Student { 
Student()
{ 
    this(20); // Calling one parameterized constructor. 
    System.out.println("0-arg constructor is called"); 
} 
Student(int a)
{ 
    System.out.println("1-arg constructor is called"); 
} 
{ 
    System.out.println("IIB is called"); 
} 
public static void main(String[] args) 
{ 
    new Student(); 
 } 
}

Output:

IIB is called 
1-arg constructor is called 
0-arg constructor is called

In this example program, we have created one instance block and two constructors. First, we check how many objects are created in the program. Since only one object is created using new Student();, the instance initialization block will execute only one time.

Although the this(20) statement calls another constructor, it does not create a new object. Therefore, the IIB is not executed again. Remember that the constructor chaining using this() does not create a new object.

The flow of execution of above program is shown in the figure below.

Order of execution of instance initializer block in Java

Important Note:

  • An instance block depends on object creation, not on constructor chaining or constructor calls. Therefore, it executes whenever an object is created.
  • IIB executes before the execution of constructor body.
  • If you create 5 objects, five times constructors are executed, but just before the constructor, five times instance blocks execute.
  • No separate memory is allocated for the IIB because it is only executable initialization code.

How to Initialize Variable Using Instance Initialization Block?


You can use an instance block to initialize the value to variables. Let’s see an example program based on it.

Example 6: Initialization of Variable Using IIB

public class Employee 
{ 
   int empId; 
// Declare an instance block to initialize the value to variable during object creation. 
   { 
     empId = 123; 
   } 
   void display()
   { 
      System.out.println(empId); 
   } 
public static void main(String[] args) 
{ 
     new Employee().display(); 
  } 
}

Output:

123

Advantage of Instance Block in Java


There are two main advantages of instance initialization block in Java. They are as follows:

  • Instance block is used to write that logic which has to be executed during object creation before the execution of constructor.
  • It is used to initialize the value to a variable.

Difference between Instance Block and Constructor in Java


There are mainly three differences between instance initialization block and constructor in Java. They are as follows:

  • Both instance block and constructor will be executed automatically for every object creation, but instance block will be executed before a constructor.
  • A constructor can take arguments, but an instance block cannot take any arguments. Hence, we cannot replace the constructor concept with IIB.
  • If we want to perform any activity for every object creation, we have to define that activity inside the instance block.
DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.