Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

Initializer block in Java

$
0
0

If you want to initialize an instance variable you will put that code in a constructor. There is one alternative to using a constructor to initialize instance variables which is called initializer block.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword.

General form of Initializer block


{
// whatever code is needed for initialization goes here
}

Usage

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors. Common code, that is used by all the constructors can be put in the initializer block.

Example code


public class InitBlockDemo {
// no-arg constructor
InitBlockDemo(){
System.out.println("no-arg constructor invoked");
}
// constructor with one param
InitBlockDemo(int i){
System.out.println("constructor with one param invoked");
}
// initializer block
{
System.out.println("This will be invoked for all constructors");
}
public static void main(String[] args) {
InitBlockDemo ibDemo = new InitBlockDemo();
InitBlockDemo ibDemo1 = new InitBlockDemo(10);

}
}

Output


This will be invoked for all constructors
no-arg constructor invoked
This will be invoked for all constructors
constructor with one param invoked

Here it can be seen that initializer block is called first before calling the constructor of the class.

That's all for this topic Initializer block in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. static block in Java
  2. Constructor chaining in Java
  3. Constructor in Java

You may also like -

>>>Go to Java Basics page


Viewing all articles
Browse latest Browse all 938

Trending Articles