Java Notes: Java Static Initializer Block

In Java, Static Initializer Block, or static block, is a block that runs kind a set of instructions when the class is allocated in the memory. This block is acting like a global instruction of all instances of the class.

public class StaticBlockExample {

In this code block, we created a class named as StaticBlockClass and initialize it inside the StaticBlockExample class. If we run the code, we should see the output Hello from the static block.

Static Block vs Constructor

Although static initializer block seems working like a constructor method, they are totally different. When we use the constructor method inside a class, it will run each instance of the class. For example;

public class StaticBlockExample {

If you run the example code above the output will be:

Hello from the static block.
Hello from the Constructor.
Hello from the Constructor.

This is because we instantiate the StaticBlockClass two times and because of that, the constructor blog runs twice. As we can see in the example, the code inside the static block executed before constructors, this is because, as I mentioned earlier, static block runs at memory allocation.

Happy Coding

Software Developer