What is a Java static block, and how does it work?

I was reviewing some Java code and came across this snippet:

static {
    // some initialization code
}

Coming from a C++ background, I had no idea what this was or why it was used. Since the code compiled without errors, I assume it serves a specific purpose. What exactly is a Java static block, and how does it function within a class?

If you’re coming from a C++ background, seeing a Java static block for the first time can be a bit confusing. But don’t worry—I’ll break it down for you in a simple way!

A static block in Java is used to initialize static variables or perform one-time setup operations when a class is loaded. It runs before the main method and executes only once, no matter how many objects of the class are created. In Java, static variables belong to the class itself, not to instances. Sometimes, you need complex logic to initialize them—this is where a static block comes in handy!

Why?

Ensures static variables are properly set up before any instance of the class is created. Useful when initialization requires more than just a simple assignment.

class StaticExample { static int number;

static { 
    number = 100;  // Setting a static variable
    System.out.println("Static block executed: number initialized to " + number);
}

public static void main(String[] args) {
    System.out.println("Main method executed.");
}

}

:small_blue_diamond: What happens here?

When the class is loaded into memory, the static block runs first and initializes number. Then, the main method executes

You can have multiple static blocks in a class. They execute in the order they appear in the file.

:white_check_mark: Why?

  • Useful when initialization needs multiple steps.
  • Allows splitting logic into organized sections.

Code Example:

class MultiStaticExample {
    static { 
        System.out.println("First static block executed.");
    }

    static { 
        System.out.println("Second static block executed.");
    }

    public static void main(String[] args) {
        System.out.println("Main method executed.");
    }
}

Both static blocks execute in order before main().

The output will be:

  • SQL Code:
  • First static block executed.
  • Second static block executed.
  • Main method executed.