Core JAVA

Instance initializer block in Java

Apart from methods and constructors, Initialization Blocks are the third place in a Java Program where operations can be performed. Initialization Blocks come in two flavors:
  1. Static Initialization Blocks: Runs first when the class is first loaded. Declared by using the keyword “Static
  2. Instance Initialization Blocks: Runs every time when the instance of the class is created.

Code Snippet:

class InitDemo
{
    static int y;
    int x;
    //Static Initialization Block
    static
    {
       y=10;
    }
   // Instance Initialization Block
   {
      x=20;
   }
}
Instance initialization block code runs right after the call to super() in a constructor, in other words, after all super constructors have run. The order in which initialization blocks appear in a class matters. If a class has more than one they all run in the order they appear in the class file.
Some rules to remember:
  • Initialization blocks execute in the order they appear.
  • Static Initialization blocks run once when the class is first loaded.
  • Instance Initialization blocks run every time a class instance is created.
  • Instance Initialization blocks run after the constructor’s call to super().

Instance initializer block:
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.

Why use instance initializer block?
Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill a complex array or error handling etc.

//Program of instance initializer block that initializes values to the instance variable

class Car{
    int speed;
    
    Car(){
        System.out.println("speed is "+speed);
      }
 
    {
         speed = 120;
    }
     
    public static void main(String args[]){
        Car c1=new Car();
        Car c2=new Car();
    }    
}

Output:
speed is 120
speed is 120

There are three places in java where you can perform operations:

  1. method
  2. constructor
  3. block

Flow of invoked of instance initializer block & constructor

class Car{
    int speed;
    
    Car(){
        System.out.println("constructor is invoked");
      }
 
    {
         System.out.println("instance initializer block invoked");
         speed = 120;
    }
     
    public static void main(String args[]){
        Car c1=new Car();
        Car c2=new Car();
    }    
}
Output:
instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked

In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the costructor after the first statement super(). So firstly, constructor is invoked. Let’s understand it by the figure given below

Rules for instance initializer block :
There are mainly three rules for the instance initializer block. They are as follows:

  1. The instance initializer block is created when instance of the class is created.
  2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
  3. The instance initializer block comes in the order in which they appear.

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago