A static initialization block is a block of code that is executed during the initial loading of a class by the JVM before the first use of any static member or instance creation of the class.
Background:
Java has provided static fields to store values common to all instances from the very beginning. For non-standard initialization or complex calculations at class startup, static blocks were introduced.
Problem:
Ordinary static fields can be initialized directly at declaration, but when initialization is lengthy, requires access to other classes/files/databases, or depends on complex logic, static blocks must be used. Improper use of static blocks can lead to unexpected behavior during class loading, difficulties in testing, and even deadlocks.
Solution:
Static blocks should only be used for complex initialization of static resources when it cannot be expressed in a single statement. A good example is loading JDBC drivers, reading configurations:
public class Config { public static Properties properties; static { properties = new Properties(); try (InputStream in = new FileInputStream("config.properties")) { properties.load(in); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } }
Key features:
Can you use return inside a static block?
No, the return statement is not allowed in static blocks. You can use throw to throw an exception.
When is the static block executed — during class loading or object creation?
The static block is executed once when the class is loaded, even if no object is created.
Can there be multiple static blocks in one class? In what order do they execute?
Yes, you can declare multiple static blocks. They execute in the order they appear in the class code.
In a class, the static block reads a large file and connects to an external service. In tests or simple utilities, the JVM class loads slowly.
Pros:
Cons:
The static block checks for software license availability at startup, throws ExceptionInInitializerError on failure.
Pros:
Cons: