A static initializer in Java is a block of code enclosed in curly braces and preceded by the static keyword. This block is executed once when the class is loaded into the JVM, before any instances of the class are created and before any static methods are called. Its main purpose is to perform complex initialization of static variables.
public class Example { static int staticValue; static { staticValue = 10; // Complex initialization logic System.out.println("Static initialization block executed"); } }
A static initializer is particularly useful when a static variable depends on other resources or requires processing at the time of class loading.
Question: "In what order are static blocks and static variable initialization executed in Java if their declaration order differs in the class?"
Correct Answer: All static variables and blocks are initialized in the order they are declared in the source code of the class (top to bottom). If a static variable is used in a static block located above its definition, it will cause a compilation error or may lead to an unexpected value.
class Order { static { System.out.println(X); // default value: 0 } static int X = 100; static { System.out.println(X); // 100 } }
Story
On a large project, a logger was initialized through a static block, however, when the declaration of variables and static blocks was rearranged, the logger variable remained uninitialized at the time of invocation, leading to a NullPointerException during logging at class load time.
Story
When developing a JDBC utility, driver initialization was done in a static block. One of the developers moved the declaration of a String variable containing the path below the static block, and the code stopped connecting to the database correctly — the path became null.
Story
In a distributed system, there were issues with loading configuration data: part of the logic was implemented through static blocks in several classes with mutual references, leading to cyclic initializations and StackOverflowError during application startup due to improper organization of static blocks and dependencies.