Static Block

Naveen AnamaneniUpdated · 4 min read

A shop sets up its price list once, when it opens in the morning, not every time a customer walks in. A static block does that for a class: it's code that runs exactly once, when the class is first initialized, to prepare static data such as lookup tables, constants that need calculation, or settings.

Set Up Once

States.java▶ Try it
import java.util.HashMap;
import java.util.Map;
 
public class States {
    static class StateCodes {
        static final Map<String, String> NAMES = new HashMap<>();
 
        static {
            NAMES.put("TS", "Telangana");
            NAMES.put("MH", "Maharashtra");
            NAMES.put("KA", "Karnataka");
            NAMES.put("TN", "Tamil Nadu");
            System.out.println("State codes loaded: " + NAMES.size());
        }
 
        static String name(String code) {
            return NAMES.getOrDefault(code, "Unknown");
        }
    }
 
    public static void main(String[] args) {
        System.out.println("Program started");
        System.out.println(StateCodes.name("TS"));
        System.out.println(StateCodes.name("KA"));
    }
}
Output
Program started
State codes loaded: 4
Telangana
Karnataka

How it works

  1. Lines 8 to 14: static { ... } is a static block. It fills the shared map once.
  2. "Program started" prints first: the class isn't initialized until it's first used, on line 23.
  3. The block runs once. The second call to name on line 24 doesn't run it again.

Map and HashMap store key-value pairs; The collections lessons, later in the course, cover them.

Try it yourself: delete lines 23 and 24. Does "State codes loaded" still print?

When Is a Class Initialized?

A class's static fields are set and its static blocks run the first time the program:

Triggers initializationExample
Creates an objectnew StateCodes()
Calls a static methodStateCodes.name("TS")
Reads or writes a static field (not a compile-time constant)StateCodes.NAMES
Initializes a subclassParents are initialized first
Runs main in itThe class with main

Several static blocks and static field initializers run top to bottom, in the order they appear.

Static Block vs Instance Block

Static blockInstance block
Written asstatic { ... }{ ... }
RunsOnce per classOnce per object
Runs whenThe class is first initializedEach new, before the constructor body
Can useOnly static membersStatic and instance members

Common Mistakes

Expecting it to run when the program starts. It runs when the class is first used.

Using instance fields in it. There's no object; only static members are available.

Putting risky work in it. A failure breaks the whole class for the rest of the program.

Interview Corner

What is a static block, and when does it run?

A static block, static { ... }, is code that runs once when the class is initialized: the first time an object is created, a static method is called or a static field is used. It's used to set up static data that needs more than a simple assignment.

Can a program print something without a main method using a static block?

Not since Java 7. The launcher looks for main before initializing the class, and reports an error if it's missing. Static blocks still run first when main exists, because the class is initialized before main is called.

Practice

  1. Easy: Use a static block to fill a static array with the squares of 1 to 10, and print squares[7].
  2. Harder: Write two classes, each with a static block that prints its name. Use only one of them in main. Which message prints?

Quick check: Static block

4 questions
1How often does a static block run?
2Which of these triggers a class's static block?
3Can a static block use instance fields directly?
4What happens if a static block throws an exception?

Key Takeaways

Was this tutorial helpful?

Lesson 108 of 482