An instance initialization block is used to initialize objects of a class.
An instance initializer is a block of code inside the body of a class, but outside any methods or constructors.
An instance initializer does not have a name.
Its code is placed inside an opening brace and a closing brace.
An instance initializer cannot have a return statement.
The following code shows how to declare an instance initializer.
class Test { private int num; // An instance initializer { this.num = 101; } }
Code for all instance initializers are executed before any constructor.
The following code demonstrates the sequence in which the constructor and instance initializers are executed.
class Main { {//from w w w . ja v a 2 s. c o m System.out.println("Inside instance initializer 1."); } { System.out.println("Inside instance initializer 2."); } public Main() { System.out.println("Inside no-args constructor."); } public static void main(String[] args) { Main m = new Main(); } }