Instance Block in Java | Types, Example

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

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

Between the opening and closing braces, we can write codes 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 as follows:

Syntax:

public class Student 
{  //  block start.
   // class body
}  // block end.

In Java, every class has a class block that groups the data and methods inside the class. Similarly, every method has a method block that contains a group of statements.

A block can also be placed within another block that is called nested block in Java, as shown in the following figure.

Block in Java

Types of blocks in Java


There are three types of blocks in Java. They are as follows:

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

Types of block in Java

Local Block in Java


A block defined inside a method, block, or constructor is called local block in Java. It is also called inner block in Java.

It will be executed whenever the enclosing method, constructor, or block is executed. It is not similar to the instance block. It cannot be static.


We can declare local block inside a method, constructor or block and can also be nested. For example, a method with the nested block is as follows:

public void methodwithInnerblock()
{  // Outer block starts here with opening braces.
  int x = 20;
  System.out.println(" Outer block");
 
  { // Inner or 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 overlap.

In the above example, a method contains two opening curly braces, indicating the start of 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


All the variables declared inside a block are local variables. Therefore, they can be accessed only within that block.

That is, the scope of these local variables will be accessed only within the block. We cannot call these variables from outside the block. For example:

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

Variable x has been declared inside the block and cannot be accessed from outside the block. Similarly, we cannot declare a variable with the same name inside an inner block if a variable with the same name has been already declared in the outer block. This is because variables declared in the outer block can always be used inside the inner block.

But if we declare a variable with the same name inside the inner block, there is no way for Java to differentiate between these two variables inside the inner block.

The following example snippet of code won’t compile.

public static void invalidRedeclarationMethod()
{    
   int num = 20;
   {
     int num = 30; // Invalid redeclaration of variable num. A compile-time error.
     int num1 = 40; // ok
   }  
}

Instance Initialization Block (Non-static block) in Java


An instance initialization block (IIB) is also known as non-static block in Java. It is used to write that logic which we want to execute during the object creation.

IIB is also used to initialize variables. It will be executed after the execution of the static block if any static block is declared inside the class.


Static and Non-static variables can be accessed inside the non-static block. Instance block executes before the constructor only when an instance of the class is created.

Declaration of Instance block in Java

An instance initialization block in Java can be declared by the following syntax:

Syntax of Instance block:
{  
 // logic here.
}

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

Program code 1:

package blockProgram; 
public class Test 
{ 
// Declare Zero parameter constructor. 
   Test() 
   { 
      System.out.println("0-arg Constructor"); 
   } 
// Declaration of an Instance block. 
   { 
      System.out.println("Instance Block"); 
   } 
public static void main(String[] args) 
{ 
 // First approach: Create the object of the class. 
    Test t = new Test(); // named object because object contains reference variable. 

 // Second approach: 
    new Test(); // nameless object. It is frequently used to reduce the length of the code. 
  } 
}
Output: 
       Instance Block 0-arg Constructor

Which is first executed Instance initialization block, or Constructor?


During the object creation time, if any instance blocks are there, First instance blocks will be executed before the execution of any constructor. Once the execution of instance block is completed, only the constructor part will be executed.

In the above example program, IIB is executed before the execution of constructor and later the constructor is executed.

What is need/use of Instance initialization block in Java?


Let’s understand the need or use of java instance initialization block with the help of an example program.

Program code 2:

package blockProgram; 
public class Simple 
{ 
// Declare a zero parameter constructor. 
   Simple() 
   { 
      System.out.println("0-arg constructor"); 
   } 
// Declare one parameter constructor with int parameter named x. 
   Simple(int x)
   { 
     System.out.println("1-arg constructor"); 
   } 
// Declare two parameters constructor with int parameter named x and y. 
   Simple(int x, int y)
   { 
      System.out.println("2-arg constructor"); 
   } 
// Declaration of an IIB. 
   { 
     System.out.println("IIB"); 
   } 
public static void main(String[] args) 
{ 
 // Create first object of class to call zero paramter constructor. 
    new Simple(); 

 // Create second object of class to call one parameter constructor and pass one argument value to its constructor.. 
    new Simple(20); 

 // Create third object of the class to call two parameters constructor and send two arguments value to its constructor.. 
    new Simple(10,20); 
  } 
}
Output: 
       IIB 0-arg constructor 
       IIB 1-arg constructor 
       IIB 2-arg constructor

Explanation:

1. In the preceding example program, there is only one instance initialization block and three constructors. The first constructor will take zero parameter, second constructor will take one parameter, and third will accept two parameters.

2. During the first object creation, instance block will be executed first. Once the execution process of instance block is completed, the 0-arg constructor will be executed.

3. During the second object creation with sending one argument value, again first instance block will be executed, and later 1-arg constructor will be executed.

4. Similarly, for third object creation, again IIB will be executed first and then 2-argument constructor will be executed.

Now you observe that on every object creation, the constructor logic is executed corresponding to the object, and also corresponding IIB is executed.

Here, the constructor logic is specific to the particular objects but instance block logic is common for all objects.

In other words, suppose we are creating 100 objects. For every object, different constructor is being executed but I would like to execute a single instance block during object creation for all objects.

This is the main use of instance initialization block in java which makes it different from the constructor.


Note: Constructor logic is specific to an object but IIB logic is common for all objects.

Order of execution of Instance blocks in Java program


In Java programming, we can declare multiple instance initialization blocks inside a class. The order of the execution of instance block will always be towards the top to bottom.

Let’s take an example program to understand the concept of order of execution of instance blocks in java.

Program code 3:

package blockProgram; 
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 program?

Program code 4:

package blockProgram; 
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(); 
 } 
}

In this example program, one IIB and two constructors have been declared. First of all, we will check how many objects are created? In this program, only one object is created. So, instance block will be executed only one time.

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

Order of execution of instance initializer block in java

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

Key Points:

1. Java Instance block depends on the object creation but does not depend on the constructor execution.

2. IIB is executed during the object creation before the constructor execution.

3. If you create 5 objects, five times constructors are executed but just before constructor, five times instance block will be executed.

4. The memory is allocated for instance block during object creation.

How to Initialize Variable using Instance Initialization Block?


Instance block is also used to initialize the value to variables. Let’s see an example program based on it.

Program code 5:

package blockProgram; 
public class Employee 
{ 
   int empId; 
// Declare 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


1. Both instance block and constructor will be executed automatically for every object creation, but instance block will be executed before a constructor.

2. A constructor can take arguments but instance block cannot take any argument. Hence, we cannot replace the constructor concept with IIB.

3. If we want to perform any activity for every object creation, we have to define that activity inside the instance block.


This tutorial has covered almost all important points related to instance initializer block in Java with example programs. Hope that you will have understood this topic and enjoyed programming. In the next, we will learn static variable in Java with the help of important example programs.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love