Course contentsShow
← Java
Lesson 368 of 2,8709. Static Members and Utility ClassesFree lesson

What Are Static Blocks?

Understanding static initializer blocks: code that runs once when a class is loaded, before any instances are created.

What Are Static Blocks?

You'll learn: How to write code that automatically runs once when your class is first loaded, before any objects are created or static methods are called.

What Is a Static Block?

A static initializer block (or static block) is a special section of code inside a class that runs exactly once: when the Java Virtual Machine first loads the class into memory. It executes before any constructors, before any static methods are called, and before any static fields are accessed.

Think of it like a "setup crew" that prepares a stage before the show begins. The crew arrives first, sets everything up once, and then the actors (your objects and methods) can perform.

Why Use Static Blocks?

You've already learned that static fields can be initialized at declaration (like static int count = 0;). But sometimes you need more complex initialization logic—maybe calculations, loops, or error handling. Static blocks let you write multiple statements to initialize static fields properly.

Syntax

class Example {
    static int value;
    
    static {
        // This code runs once when the class loads
        value = 10 * 5;
        System.out.println("Static block executed!");
    }
}

When the JVM loads Example for the first time (whether to create an instance or call a static method), the static block executes immediately. Only once, ever.

Multiple Static Blocks

You can have multiple static blocks in a class. They execute in the order they appear in your code, from top to bottom, just like instance initializer blocks.

Key Takeaway: Static blocks run once when a class is loaded, allowing complex initialization of static fields before any part of your class is used.