CodeBlanks Logo Icon CodeBlanks

static block

Learn class initialization with static blocks.

static block

A static block runs once when the class is loaded. It is used to initialize static fields; especially for computations done in multiple steps. It is written as static { }.

Example: class Config { static double rate; static { rate = 1.5; } }. Here the static block assigns 1.5 to rate. When the class is loaded, this block runs once; all instances see the same value. A static block is useful when initialization requires more than a simple assignment. If multiple static blocks exist, they run in order from top to bottom.

When to use a static block?

A static block is used when a static field cannot be initialized with a simple value. For example, when a computation, file reading or external source is needed. A static block gathers this complex initialization in one place.

Example: static List<Integer> data; static { data = new ArrayList<>(); data.add(10); data.add(20); }. Here the data list is populated inside the static block. When the class loads, the list is ready. This is a multi-step initialization that cannot be done with a single static List<Integer> data = new ArrayList<>(); line. A static block organizes initialization logic at the class level.

Practice Add a static block to Config

Define a class Config. Add a static int base field (no initial value). Add a static block; its body runs base = 100;. In main print the value of Config.base.

Starter code

Main.java
// Define the Config class
// Add a static base field and a static block
// Print the base value in main

Sample solution

Main.java
class Config {
    static int base;
    static {
        base = 100;
    }
    public static void main(String[] args) {
        System.out.println(Config.base);
    }
}

Expected output

100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does a static block run?

  • Every time an instance is created
  • Once when the class is loaded Correct answer
  • When a method is called
  • When the program ends

Explanation: A static block runs once when the class is loaded.

2 Complete the static block

Question
class Config {
    static double rate;
    ____ {
        rate = 1.5;
    }
}
Answer
class Config {
    static double rate;
    static {
        rate = 1.5;
    }
}

Explanation: A static block runs during class loading.

3 Match the static block parts

Term Meaning
static { } Block syntax
class load Run time
rate = 1.5 Initialization
once Run frequency

All lessons in Intermediate