In Java, an Instance Initialization Block (IIB) is used to initialize instance-level data and executes every time an object is created, before the constructor. It helps run common initialization logic shared across multiple constructors and ensures consistent object setup.
class GFG {
{
System.out.println("IIB executed");
}
GFG() {
System.out.println("Constructor executed");
}
public static void main(String[] args) {
GFG obj = new GFG();
}
}
Output
IIB executed Constructor executed
Explanation: The Instance Initialization Block (IIB) runs automatically before the constructor every time an object is created
Syntax
{
// statements
}
Execution Order of IIB
When an object is created:
- Instance variables are initialized
- Instance Initialization Block executes
- Constructor executes
Example 1: Multiple Instance Initialization Block
class GfG {
{ System.out.println("IIB1 block"); }
{ System.out.println("IIB2 block"); }
{ System.out.println("IIB3 block"); }
GfG() {
System.out.println("Constructor Called");
}
public static void main(String[] args) {
GfG a = new GfG();
}
}
Output
IIB1 block IIB2 block IIB3 block Constructor Called
Explanation:
- Multiple IIBs execute in the order they appear in the class.
- Constructor executes after all IIBs.
Example 2: Instance Initialization Block with Parent Class
class B {
B() { System.out.println("B-Constructor Called"); }
{ System.out.println("B-IIB block"); }
}
class A extends B {
A() {
super();
System.out.println("A-Constructor Called");
}
{ System.out.println("A-IIB block"); }
public static void main(String[] args) {
A a = new A();
}
}
Output
B-IIB block B-Constructor Called A-IIB block A-Constructor Called
Explanation:
- Creating new A() starts object initialization.
- Parent class B IIB executes first.
- Parent class B constructor runs next.
- Child class A IIB executes after parent constructor.
- Child class A constructor runs last.