🔹 1️⃣ What Is a Static Block?
A static block (also called a static initializer) is a block of code inside a class that is executed when the class is loaded into memory.
- Runs only once, regardless of how many objects you create.
- Can be used to initialize static variables or perform class-level setup.
Syntax:
class MyClass {
static {
// code executed when the class is loaded
System.out.println("Static block executed");
}
}
🔹 2️⃣ Execution Order
- Static variables and static blocks are executed in the order they appear in the class.
- Static blocks run before the main method or any instance constructors.
Example:
class Demo {
static int count;
static {
count = 5;
System.out.println("Static block 1, count = " + count);
}
static {
count = 10;
System.out.println("Static block 2, count = " + count);
}
public static void main(String[] args) {
System.out.println("Main method, count = " + count);
}
}
Output:
Static block 1, count = 5
Static block 2, count = 10
Main method, count = 10
➡️ Static blocks execute in text order, before main()
.
🔹 3️⃣ Use Cases for Static Blocks
- Initialize static variables that require complex logic:
class Config {
static Map<String, String> settings = new HashMap<>();
static {
settings.put("url", "https://example.com");
settings.put("timeout", "5000");
}
}
- Load external resources (files, DB drivers):
class DBConnection {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
- Perform one-time setup for the class.
🔹 4️⃣ Key Points
Feature | Notes |
---|---|
Execution time | When class is loaded by JVM |
Runs how many times? | Only once per class, no matter how many objects are created |
Can access instance variables? | ❌ Only static members can be accessed |
Multiple static blocks? | ✅ Executed in top-to-bottom order in the class |
Exception handling | You must handle checked exceptions inside the block |
🔹 5️⃣ Difference Between Static Block and Constructor
Feature | Static Block | Constructor |
---|---|---|
Runs | When class is loaded | When an object is created |
Execution count | Once per class | Every object creation |
Can access | Only static members | Both static and instance members |
Purpose | Class-level initialization | Object-level initialization |
🔹 6️⃣ Example With Multiple Objects
class Test {
static {
System.out.println("Static block executed");
}
Test() {
System.out.println("Constructor executed");
}
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
}
}
Output:
Static block executed
Constructor executed
Constructor executed
✅ Static block runs once, constructors run for each object.
✅ Summary
- Static blocks run once when the class is loaded.
- They are used to initialize static variables, load resources, or perform one-time setup.
- Executed before main() and before any constructors.
- Multiple static blocks run in the order they appear.