Initializer Block in Java

When you create an instance of a class, constructor is called to initialize the instance variables. An alternative to using a constructor to initialize instance variable is to use initializer block in Java.

Initializer block is always executed when an instance of the class is created.

General form of Initializer block in Java

How to use initializer block in Java

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code if you have overloaded constructors in your class. Putting the common code in an initializer block ensures that that piece of code is always executed irrespective of the constructor called.

Initializer block Java example

Output

As you can see whether no-arg constructor is called or the constructor with single argument is called for initialization of the object, initializer block is always executed.

That’s all for the topic Initializer Block in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.