Instance initializer in Java is used for initializing the instance variables inside a class. It is a simple block without any modifiers used inside any class. If you declare a instance variable with value, then this value can be overridden in the instance initializer or in the constructor. The order of the execution as follows:
- Static initializer
- Instance initializer
- Constructor
- Variable initializer
The very common confusion is that what is difference between instance initializer and constructor and why it is used.
- If you have a code which needs fancy calculations or exception handling, then you have to use this block since normal initialization will not do. However the same code can be written inside a constructor.
- You can not explicitly throw exception from this block, since it doesn’t return the control there is no one to handle the exception thrown. You would get the compile time error “initializer does not complete normally”.
- However, you can write a code which can throw the exceptions, you must handle that exception in each constructor.
- If your class has the multiple constructors then the common initialization has to be repeated for every constructor. If you write the same code in the initializer, it executes for every constructor call. It is one of the reason why we need instance initializer.
- Instance initializer executes before the constructor calls.
- Another advantage of this are to use within the anonymous inner classes, where you can not declare any constructors.
Look at the below example:
package javabeat.net.core; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class InstanceInitializer { int i = 20; //Variable Initializer public InstanceInitializer() throws FileNotFoundException,IOException{ i = 30; System.out.println("Constructor Called"); } { i = 10; System.out.println("Instance Initializer Called"); File f=new File("test-file.txt"); FileOutputStream fo=new FileOutputStream(f); fo.write(10); } static{ System.out.println("Static Initializer Called"); } public static void main (String args[]) throws IOException{ System.out.println(new InstanceInitializer().i); } }
Output of the above example is:
Static Initializer Called Instance Initializer Called Constructor Called 30
I hope the above definition would have cleared your confusion about the instance initializers. If you have any questions, please write it in the comments section.