What is a static initialization block and why would you use one?
Short answer
A static {} block runs once when the class is defined, letting you run multi-step setup logic for static fields that a simple assignment can't express — including try/catch around initialization.
Advertisement
AModel answer
A static {} block runs once when the class is defined, letting you run multi-step setup logic for static fields that a simple assignment can't express — including try/catch around initialization.
class Config {
static settings;
static {
try {
Config.settings = JSON.parse(loadConfigString());
} catch {
Config.settings = {};
}
}
}Real-world example
Loading and validating shared configuration once when a class module is first imported.
Likely follow-ups
- Can a class have multiple static blocks?
Related topics