Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

Before a restaurant opens each morning, they do one-time setup — clean tables, stock kitchen, turn on lights. This setup happens ONCE when the restaurant opens, not every time a customer walks in. That's a static block.

What is a Static Block?

A static block executes AUTOMATICALLY and ONCE when the class is loaded into JVM memory — before any object is created or any method is called.
java
QUBITS OF DPK
1class Database {
2    static String url;
3    static String user;
4
5    static {                              // Static Block
6        System.out.println("Class loading...");
7        url  = "jdbc:mysql://localhost/db";
8        user = "root";
9        System.out.println("DB configured!");
10    }
11
12    Database() {
13        System.out.println("Object created.");
14    }
15}

Execution Order

javascript
QUBITS OF DPK
1Class is loaded
23Static variables initialized
45Static Block executes   ← ONCE only
67new Object() called
89Constructor runs        ← per object

Dry Run Example

java
QUBITS OF DPK
1class Main {
2    static { System.out.println("Static block"); }  // runs FIRST
3
4    public static void main(String[] args) {
5        System.out.println("Main started");
6        Database db1 = new Database();
7        Database db2 = new Database();
8    }
9}
Output:
javascript
QUBITS OF DPK
1Static block        ← once, before main
2Main started
3Class loading...
4DB configured!
5Object created.      for db1
6Object created.      for db2

Multiple Static Blocks

java
QUBITS OF DPK
1static {
2    System.out.println("First");   // runs first
3}
4static {
5    System.out.println("Second");  // runs second
6}
7// Output: First → Second (in order)

Static Block vs Constructor

Production Use Cases

java
QUBITS OF DPK
1// 1. Loading DB configuration once
2static {
3    url = System.getenv("DB_URL");
4    password = System.getenv("DB_PASSWORD");
5}
6
7// 2. Loading native libraries
8static {
9    System.loadLibrary("nativeLib");
10}
11
12// 3. JDBC Driver registration (classic)
13static {
14    Class.forName("com.mysql.jdbc.Driver");
15}
16
17// 4. Complex static variable initialization
18static {
19    SUPPORTED_CURRENCIES = new HashSet<>();
20    SUPPORTED_CURRENCIES.add("USD");
21    SUPPORTED_CURRENCIES.add("INR");
22    SUPPORTED_CURRENCIES.add("EUR");
23}

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — Static block runs before main in SAME class
2class Main {
3    static { System.out.println("Static"); }  // prints FIRST
4    public static void main(String[] args) {
5        System.out.println("Main");            // prints SECOND
6    }
7}
8
9// Trap 2 — Cannot access instance variables
10static {
11    System.out.println(instanceVar);  // ❌ no object exists!
12}
13
14// Trap 3 — Multiple blocks run in ORDER top to bottom
15
16// Trap 4 — Runs ONCE regardless of how many objects created

Interview Answer (SDE-2)

"A static block is a one-time initialization block that executes automatically when the class is loaded into JVM — before main method and before any object is created. It runs exactly once regardless of how many objects are created. Multiple static blocks execute in top-to-bottom order. Used for class-level setup like loading configuration, registering JDBC drivers, or initializing complex static data structures. Key distinction: constructor runs per object, static block runs per class load."

Interview Questions & MAANG-Level Answers

Q1. When does a static block execute?
A static block executes when the class is loaded into JVM memory — before any object is created, before main() runs (even if static block is in the same class), before any static method is called. Class loading happens the first time the class is referenced: first object creation, first static method call, or first static field access.
Q2. How many times does a static block run?
Exactly once per class load — regardless of how many objects you create. If you create 1000 objects, the static block still runs only once. The JVM guarantees this. Multiple static blocks in the same class all run once each, in top-to-bottom order.
Q3. What is the difference between static block and constructor?
Static block: runs once when class loads, before any object, no this reference, used for class-level one-time setup (load config, register drivers). Constructor: runs every time an object is created with new, has this reference, used for object-level initialization. Execution order: static variables init → static block → ... → new called → instance variables init → constructor body.
Q4. Can a static block access instance variables?
No. Static block runs before any object exists, so there's no this reference and no instance variables to access. static { System.out.println(this.name); } — compile error. Static blocks can only access static variables and static methods. To work with instance data, you must create an object inside the static block: static { MyClass obj = new MyClass(); System.out.println(obj.name); }.
Q5. If a class has both a static block and main(), which runs first?
The static block runs FIRST, even if it's defined after main():
java
QUBITS OF DPK
1class Main {
2    static { System.out.println("Static block"); }  // prints 1st
3    public static void main(String[] args) {
4        System.out.println("Main method");           // prints 2nd
5    }
6}
7// Output:
8// Static block
9// Main method
This is because the JVM loads the class (triggering static block) before calling main(). Classic interview trap!