Static Block in Java

(Last Updated On: March 8, 2019)

Learn Static Block in java programming with example.

A class can have a Static block, where we perform some operations or write some statements, if we want them to call before calling constructor of the class.

Here is the static block defined in the class X. Just write the keyword static and put braces {}

 

Note that static block is different that static method in java language.

POINTS TO NOTE:

  • It gets executed only once and when the class is loaded in the memory.
  • A class can have multiple Static blocks and they are executed in the same sequence in which they have been written into the program.
  • Note that static blocks executed before main method is called by the compiler which is the starting point of a program.
  • Also, Order of static blocks and constructor is that static blocks get called before class constructor,
  • We know that when we create an object of the class then construct gets called. But, if we have any one or more static block in the class, then all static blocks will be called before constructor of the class.

 

Static Block Example

In below program example, the class X contains one static block and one constructor. In main method, on object creation, first the static block will be called and then the constructor.

Output:
Static Block-1 …
Constructor…

 

Multiple Static Blocks Example

In this example, the class X contains two static blocks and one constructor. as an output, first, static block-1 and then static block-2 will be called. after that constructor will be called.

Output:
Static Block-1 …
Static Block-2 …
Constructor…

 

Java Static Block Vs Constructors

Static block is called only once when JVM loads the class into memory. Whereas, constructor will be called every time when we create an object of the class.

Code Example:

Below, we have one static block and one class constructor in java program. We are creating three objects of the class X.

Notice the output of the given program that static block has been called one time and constructor of the class three times.

Output:
Static Block…
Constructor…
Constructor…
Constructor…

 

NOTE:

It is not important that you always write static block first and then constructor. You can write in any order you want in the class.