Scientech Easy Instance Initialization Block(IIB) in Java with Example | Scientech Easy

Thursday, September 6, 2018

Instance Initialization Block(IIB) in Java with Example

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. 
For example, Here is a set of code with a block within a method.
    
     void m1() { //  block start.
        // statements.
      } // block end.

Types of block in Java


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

Local Block


➲ Block defined inside a method or block or constructor is called local block or inner block.
➲ It will be executed whenever the enclosing methods or constructor or block is executed.
➲ It is not similar to the instance block. 
➲ It cannot be static.
➲ You can write local blocks inside a method or constructor or block and can also be nested.

For example, A method with the nested block.
  public void methodwithinnerblock()
   {      // Outer block starts with openeing braces.
      int x=20;
     System.out.println(" Outer block");
   
     {   // Inner or local block starts with next opening braces.
         int y=30;
      System.out.println("Inner block");
         } // Inner block ends.
  } // Outer block ends.

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 last closing brace pair define the outer block. whereas the second opening brace and first closing brace pair define the inner or local block.
Thus, we can nest a block statement inside another block statement.

Scope of the variables


All the variables declared inside the 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 and you 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); // A compile time error. Varaible 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 snippet of code won't compile:
For example
   public static void invalidRedeclarationMethod() {    
     int num=20;
   {
       int num=30; // Invalid redeclaration of variable num. A compile-time error.
       int num1=40; // ok
    } 
 }

Instance Block(Non-Static Block)


Instance block are also known as instance initialization block.
It is used to write those logics which you want to execute during the object creation.
IIB is also used to initialize the variables.
IIB execute after the static block if any static block is declared.
Static and Non-static variable both can be accessed inside the non-static block. 
➲ Instance block executes only when an instance of the class is created and before the constructor.
Syntax of Instance block:
   {  
       // logics here.
      
     }
Let's see a simple example.
Program source code 1: 
    package com.scientecheasy; public class Test { // Declare Zero parameter constructor. Test() { System.out.println("0-arg Constructor"); } // Declare 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

What is invoked first instance initialization block or constructor? 


During the object creation time, if any instance blocks are there, First instance blocks are executed before any constructor. Once the execution of instance blocks are completed, only the constructor part will be executed. In the above example, IIB is executed before execution of the constructor and later the constructor is executed. 

What is the need/use of instance block in Java?               


Let's understand this by taking a simple example.
Program source code 2:
    package com.scientecheasy; public class Simple { // Declare the 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"); } // Declare 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 the second object of the class to call one parameter constructor and pass one argument value. new Simple(20); // Create the 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 this program, there are only one IIB and three constructors such as zero parameter, one parameter, and two parameter constructors. During the first object creation, IIB is executed. 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 is executed, and later the 1-arg constructor will be executed. Similarly, for third object creation, again IIB is executed and then the 2-argument constructor will be executed. 

Now you will notice that every object creation, the constructor logic is executed corresponding to the object and also corresponding IIB is executed. Here, You can think that 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 different from the constructor. 
Always Remember: Constructor logic is specific to an object but IIB logic is common for all objects.

What is the order of the execution of blocks in Java programming?


In Java programming, You can declare multiple instance block inside the class and the order of the execution of IIB will always be from top to bottom.  Let's take one more example to understand it.
Program source code 3:
    package instanceBlockExp; 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
Program source code 4:
    package instanceBlockExp; public class Student { Student(){ this(20); 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, One IIB and two constructors are executing. So in this case, What is the output? (very important program).
You can solve this question very easily. First of all, you check that How many objects are created? In this example, only one object is created. So IIB will be executed only one time.
You can see the flow of execution in the below image.
Instance Initialization Block(IIB) in Java with Example programs, What is a block?, Types of the block, Instance block vs Constructor, Uses, and advantages of instance block.
Instance block example

    Output: IIB is called 1-arg constructor is called  0-arg constructor is called
Always Remember:
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 the variable by using IIB?


Instance block is also used to initialize the value to a variable. Let's see a simple example program to understand it.
Program source code 5: 

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

Advantages of Instance initialization block


1. To write the logic. That logic which is 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 1st followed by a constructor.
2. A constructor can take arguments but instance block cannot take any arguments. 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:
I hope that this article will help you to understand the basic concept of Instance Initialization Block with example programs. We have covered almost all topic related to IIB. So practice all important programs. Later on, the Static block will be discussed in a further tutorial. 

Next ➝ Static in Java                                                              Scientech Easy loves you 

Hot Post

Java Collections Framework | Need & Advantages