Java
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.
Exercise 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.
Show example solution
class Config {
static int base;
static {
base = 100;
}
public static void main(String[] args) {
System.out.println(Config.base);
}
}
Test yourself
-
When does a static block run?
- Every time an instance is created
- Once when the class is loaded
- When a method is called
- When the program ends
Show answer
Once when the class is loaded — A static block runs once when the class is loaded.
-
Complete the static block
class Config {
static double rate;
____ {
rate = 1.5;
}
}
Show answer
class Config {
static double rate;
static {
rate = 1.5;
}
}
-
Match the static block parts
- static { }
- Block syntax
- class load
- Run time
- rate = 1.5
- Initialization
- once
- Run frequency
Next lesson: Class variables