Tuesday, July 9, 2019

Java Static Initialization vs. Instance Initialization - When to use which?


Static Initialization

Typically static initialization block is used to initialize static variables of a class. The block is called at the time of class initialization. It is called only once. You can initialize static variables inline. If more complicated logic is required for initialization, a static initialization block can be used. The static initialization blocks are called in the order in which they occur, and they are called before the constructors.

For example:


The output of the above code is as shown below.


Instance Initialization

Instance Initialization or Initializer Block is called whenever an instance of the class is created.
It can be used to execute code that is common to all constructors. This block is executed before the constructor is executed.

For example:

The output of the above code is as shown below.


Ref: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

No comments :

Post a Comment