0
0
JavaConceptBeginner · 3 min read

What is Static Block in Java: Explanation and Example

A static block in Java is a block of code inside a class that runs only once when the class is first loaded. It is used to initialize static variables or perform setup tasks before any objects are created or static methods are called.
⚙️

How It Works

Think of a static block as a special setup step that happens automatically when your Java program loads a class, even before you create any objects from that class. It runs only once, like turning on the lights before you start working in a room.

This block is useful for preparing things that belong to the class itself, not to any single object. For example, if you want to set up some shared settings or load data that all objects will use, the static block is the place to do it.

Because it runs when the class loads, it helps ensure that important setup is done early and only once, saving time and avoiding repeated work.

💻

Example

This example shows a static block initializing a static variable. When the class loads, the static block runs and sets the value before the main method prints it.

java
public class StaticBlockExample {
    static int number;

    static {
        number = 10;
        System.out.println("Static block executed: number initialized");
    }

    public static void main(String[] args) {
        System.out.println("Value of number: " + number);
    }
}
Output
Static block executed: number initialized Value of number: 10
🎯

When to Use

Use a static block when you need to initialize static variables with complex logic or when setup must happen once before the class is used. For example:

  • Loading configuration settings from a file.
  • Setting up database connections shared by all instances.
  • Initializing static constants that require calculations.

This helps keep your code organized and ensures important setup runs only once.

Key Points

  • A static block runs once when the class is loaded.
  • It is used to initialize static variables or perform setup tasks.
  • Static blocks run before the main method or any object creation.
  • You can have multiple static blocks; they run in order.
  • Static blocks help prepare the class environment early.

Key Takeaways

A static block runs once when the class loads to initialize static data.
Use static blocks for complex static variable setup or one-time class initialization.
Static blocks execute before any object is created or main method runs.
Multiple static blocks run in the order they appear in the class.
Static blocks help ensure shared resources are ready before use.