- Static Initialization Blocks: Runs first when the class is first loaded. Declared by using the keyword “Static”
- 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; } }
- 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(); } }
speed is 120
speed is 120
There are three places in java where you can perform operations:
- method
- constructor
- 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(); } }
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:
- The instance initializer block is created when instance of the class is created.
- The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
- The instance initializer block comes in the order in which they appear.