In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created.
The initializer block contains the code that is always executed whenever an instance is created and it runs each time when an object of the class is created. There are 3 areas where we can use the initializer blocks:
- Constructors
- Methods
- Blocks
Tip: If we want to execute some code once for all objects of a class then we will be using Static Block in Java
Example 1:
Java
// Java Program to Illustrate Initializer Block // Class class Car { // Class member variable int speed; // Constructor Car() { // Print statement when constructor is called System.out.println( "Speed of Car: " + speed); } // Block { speed = 60 ; } // Class member method public static void main(String[] args) { Car obj = new Car(); } } |
Speed of Car: 60
Example 2:
Java
// Java Program to Illustrate Initializer Block // Importing required classes import java.io.*; // Main class public class GFG { // Initializer block starts.. { // This code is executed before every constructor. System.out.println( "Common part of constructors invoked !!" ); } // Initializer block ends // Constructor 1 // Default constructor public GFG() { // Print statement System.out.println( "Default Constructor invoked" ); } // Constructor 2 // Parameterized constructor public GFG( int x) { // Print statement System.out.println( "Parameterized constructor invoked" ); } // Main driver method public static void main(String arr[]) { // Creating variables of class type GFG obj1, obj2; // Now these variables are // made to object and interpreted by compiler obj1 = new GFG(); obj2 = new GFG( 0 ); } } |
Common part of constructors invoked !! Default Constructor invoked Common part of constructors invoked !! Parameterized constructor invoked
Note: The contents of the 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, the initializer block is always executed before the constructor.
For more details about the Instance Initialization in Java, refer to the article Instance Initialization Block (IIB) in Java
This article is contributed by Ashutosh Singh. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar 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.