Skip to main content

Understanding Static Blocks in Java: A Beginner's Guide

A static block is a block of code that is executed when a class is loaded into memory, before any object of the class is created. Static blocks can be used to initialize static variables or perform one-time operations that need to be done before the class can be used.

Principles of Static Blocks

The principles behind static blocks are:

  • A static block is a block of code that is executed when a class is loaded into memory.
  • Static blocks are executed in the order they are defined in the class.
  • Static blocks can be used to initialize static variables or perform one-time operations that need to be done before the class can be used.

Example of a Static Block


public class MyClass {
    private static int myStaticVariable;
    
    static {
        myStaticVariable = 42;
        System.out.println("Static block executed.");
    }
    
    public static void main(String[] args) {
        System.out.println("My static variable value is: " + myStaticVariable);
    }
}
			

In the above example, the MyClass class has a static block that initializes the myStaticVariable static variable to 42 and prints "Static block executed." to the console. When the class is loaded into memory, the static block is executed before any object of the class is created.

The main() method of the class accesses the myStaticVariable static variable and prints its value to the console.

Comments