All topics
library
intermediate

Static & Instance Initializer Blocks

Understand when and why to use static initializers, instance initializers, and their execution order.

Java has two types of initializer blocks that run automatically:

Static initializer = setting up a classroom once before the school year (class loading). Instance initializer = the daily setup routine each morning (each new object). Constructor = the teacher's specific instructions after setup.

Key Concepts

1
Static initializer block: runs once when the class is loaded. Used for complex static field initialization.
2
static { // runs once, when class is first loaded }
3
Instance initializer block: runs every time an instance is created, before the constructor body.
4
{ // runs before EVERY constructor }
5
Execution order: 1. Static initializer blocks (once, when class is loaded, in declaration order) 2. Instance initializer blocks (each construction, in declaration order) 3. Constructor body
6
With inheritance: parent static init → child static init → parent instance init → parent constructor → child instance init → child constructor.
7
Use cases for static blocks: - Loading native libraries: System.loadLibrary("mylib") - Populating static Maps/Sets with complex initialization - Registering JDBC drivers (legacy) - Computing static constants that require multi-step initialization
8
Instance blocks are rare — usually replaced by constructor logic or field initializers. They're most useful when multiple constructors share initialization code.
9
In modern Java, static factory methods and enum constructors often replace static initializer blocks.