Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class. For example,
import java.io.*; public class GFG { // Initializer block starts.. { // This code is executed before every constructor. System.out.println("Common part of constructors invoked !!"); } // Initializer block ends public GFG() { System.out.println("Default Constructor invoked"); } public GFG(int x) { System.out.println("Parametrized constructor invoked"); } public static void main(String arr[]) { GFG obj1, obj2; obj1 = new GFG(); obj2 = new GFG(0); } } |
Output:
Common part of constructors invoked!! Default Constructor invoked Common part of constructors invoked!! Parametrized constructor invoked
We can note that the contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents)
The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor. See this for example.
Refer below article for more details in instance initialization:
Instance Initialization Block (IIB) in Java
What if we want to execute some code once for all objects of a class?
We use Static Block in Java
This article is contributed by Ashutosh Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Method and Block Synchronization in Java
- Instance Initialization Block (IIB) in Java
- Initialization of local variable in a conditional block in Java
- Static Block and main() method in Java
- Constructor Overloading with Static Block in Java
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java.Lang.Float class in Java
- Java.io.BufferedInputStream class in Java
- Java.io.ObjectInputStream Class in Java | Set 1
- Java.util.BitSet class in Java with Examples | Set 1
- Java.io.File Class in Java
- Java.io.BufferedWriter class methods in Java
- Java.io.DataOutputStream in Java
- Java.io.StreamTokenizer Class in Java | Set 1
- Java.io.InputStream Class in Java
- Java.io.SequenceInputStream in Java
- Java.io.StreamTokenizer Class in Java | Set 2
- Java.io.Console class in Java
- Java.io.FilterOutputStream Class in Java
- Java.io.StringWriter class in Java

