Instance Initialization Block (IIB) in Java

What is 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 method is as follows:
     void m1( ) 
       { //  block start.
           // statements.
       } // block end.

Types of blocks in Java

There are three types of blocks in Java. They are as follows:
1. Local Block
2. Instance Block
3. Static Block

Types of blocks 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.

You 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 the block are local variables. Therefore, they can be accessed only within that block i.e. the scope of these local variables will be accessed only within the block but 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 the variables declared in the outer block can always be used inside the inner block.

But if you 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 is also known as non-static block in Java. It is used to write those logic which you want to execute during the object creation. IIB is also used to initialize variables. It will be executed after the execution of static block if any static block is declared.

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

Declaration of IIB in Java

An instance initialization block in Java can be declared by the following syntax.  
Syntax of Instance block:
       // logic here.

Let’s see a simple example program where we will declare an instance initialization block and constructor inside a class Test.
Program source code 1:

    package com.scientecheasy; 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 any constructor. Once the execution of instance block is completed, only the constructor part will be executed.
In the above example, IIB is executed before the execution of the constructor and later the constructor is executed. 

What is need/use of instance block in Java?               

Let’s take an example program to understand the need or use of instance initialization block in java programming.
Program source code 2:

    package com.scientecheasy; 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 the class to call zero paramter constructor. new Simple(); // Create second object of the class to call one parameter constructor and pass one argument value. new Simple(20); // Create third object of the class to call two parameters constructor and send two arguments value. new Simple(10,20); } }
    Output: IIB 0-arg constructor IIB 1-arg constructor IIB 2-arg constructor

In the preceding example program, there are only one IIB and three constructors. The first constructor will take zero parameters, second constructor will take one parameter, and third will accept two.

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

During the second object creation with sending one argument, again first IIB will be executed, and later the 1-arg constructor will be executed. Similarly, for third object creation, again IIB will be executed first and then the 2-argument constructor will be executed.

Now you will 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 and for every object, the different constructor is executing but I would like to execute a single instance block during object creation for all objects. This is the main use of IIB 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 programming

In Java programming, we can declare multiple instance initialization blocks inside a class and the order of the execution of IIB 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 source code 3:

    package com.scientecheasy; 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 source code 4:

    package com.scientecheasy; 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, since 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 IIB 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 Iiitialization block in Java
    Output: IIB is called 1-arg constructor is called 0-arg constructor is called

1. 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 IIB?

Instance block is also used to initialize the value to a variable. Let’s see an example program related to it.
Program source code 5:
    package com.scientecheasy; 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 initialization block in Java

There are two main advantages of instance initialization block in java. They are as follows:
1. IIB is used to write that logic which has to be executed during object creation before the execution of constructor.
2. IIB 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 constructor concept with IIB.
3. If you want to perform any activity for every object creation, we have to define that activity inside the instance block.

Final words
Hope that this tutorial will have helped you to understand the basic concept of instance initialization block in java with example programs. We have covered almost all important points and example programs related to this topic. I hope that you will have enjoyed programming.
Thanks for reading!

Next ➤ Static variable in Java⏪ PrevNext ⏩

Leave a Comment