Static blocks
28 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A class needs its tax rates or settings ready before anyone uses it, and only once. A constructor runs for every object, so it is the wrong place.
Why a static block?
A static block, written static { ... } inside a class, is code that runs only once, when the class is first loaded. It is used to set up the class's static fields.
A metro fare table needs a loop to fill, and a constructor would refill it for every object. A static block, static { ... }, holds setup that runs once for the whole class.
Example 1 · Filling a fare table in a static block
class MetroFare { private static int[] fares = new int[6];
static { fares[1] = 10; for (int zone = 2; zone <= 5; zone++) { fares[zone] = fares[zone - 1] + 10; } }
static int fareFor(int zones) { return fares[zones]; }}
public class MetroDemo { public static void main(String[] args) { System.out.println("1 zone: Rs. " + MetroFare.fareFor(1)); System.out.println("3 zones: Rs. " + MetroFare.fareFor(3)); System.out.println("5 zones: Rs. " + MetroFare.fareFor(5)); }}1 zone: Rs. 10 3 zones: Rs. 30 5 zones: Rs. 50
What this code does
- The loop needs several lines, so it goes in a static block, not in the field line.
- The table is filled once, at the first call to
MetroFare.fareFor, and every later call reuses it.
For one simple value, a field line like static int seats = 72; is enough. Use a static block when the setup needs a loop or several steps: fare tables, grade cut-offs or other fixed data.
When does it run?
Java runs a class's static block once, when it first loads the class for use: at the first new, the first static method call, or the first read or change of a static field.
Example 2 · The main class's static block runs before main
public class StaticFirstDemo { static { System.out.println("Static block runs"); }
public static void main(String[] args) { System.out.println("main starts"); }}Static block runs main starts
What this code does
- To call
main, Java must first use the classStaticFirstDemo, so its static block runs first. - The static block is written before
mainhere, but it would run first even if written after it.
Example 3 · Two static blocks run top to bottom
class Config { static int maxUsers = 100;
static { System.out.println("Block 1: " + maxUsers); maxUsers = 200; }
static { System.out.println("Block 2: " + maxUsers); }
static int getMaxUsers() { return maxUsers; }}
public class TwoBlocksDemo { public static void main(String[] args) { System.out.println("Calling Config"); System.out.println("Max users: " + Config.getMaxUsers()); System.out.println("Max users: " + Config.getMaxUsers()); }}Calling Config Block 1: 100 Block 2: 200 Max users: 200 Max users: 200
What this code does
- The first call to the static method
getMaxUsers()triggers the setup: the field value, block 1, then block 2, in written order. - The second call does not run the blocks again.
If a class is never used, its static block never runs. The class that holds main is used first of all, so its static block runs even before main (Example 2). Several static blocks run top to bottom, mixed with static field values in written order (Example 3). Step through the moment of first use below.
Trace the code
Watch the class load at its first use
Variables
None yet.
Output
main starts
Line 16main runs first. Exam has not been used yet, so none of its code has run.
Instance initializer blocks
An instance initializer block is a block { ... } written inside a class without static. It runs every time an object is created, just before the constructor body.
A block written as plain { ... } inside a class, without static, is an instance initializer block. It runs every time an object is created, just before the constructor body.
Example 4 · An instance block runs for every object
class Ticket { int seat = 1;
{ System.out.println("Instance block: seat " + seat); seat = seat + 10; }
Ticket() { System.out.println("Constructor: seat " + seat); }}
public class InstanceBlockDemo { public static void main(String[] args) { new Ticket(); new Ticket(); }}Instance block: seat 1 Constructor: seat 11 Instance block: seat 1 Constructor: seat 11
What this code does
- The field value
seat = 1is set first; then the instance block prints 1 and adds 10, so the constructor sees 11. - The second object goes through the same steps: an instance block runs for every
new, not once like a static block.
Field values like int seat = 1; and instance blocks run top to bottom, in written order. Instance blocks are rare in real code, because a constructor is clearer, but they appear in code-tracing questions.
The full order
This Student class has a static block, an instance block and a constructor, written in the "wrong" order. The kind of code decides when it runs, never its position in the file.
Example 5 · Static block, instance block and constructor
class Student { Student() { System.out.println("3. Constructor"); }
{ System.out.println("2. Instance block"); }
static { System.out.println("1. Static block"); }}
public class OrderDemo { public static void main(String[] args) { new Student(); System.out.println("--"); new Student(); }}1. Static block 2. Instance block 3. Constructor -- 2. Instance block 3. Constructor
What this code does
- The blocks are written in the "wrong" order, yet the static block runs first, then the instance block, then the constructor.
- For the second object, only the instance block and the constructor run again.
Java always follows this order:
- First use of the class: static field values and static blocks, top to bottom, once.
- Each
new: instance field values and instance blocks, top to bottom. - Then the constructor body for that object.
The next new repeats steps 2 and 3 only; static setup never repeats.
What a static block can and cannot do
A shop's static block tries to print the shop's name. A static block is static code: it runs once, with no object, so it can use static fields and static methods, but not instance fields or this.
Example 6 · Mistake: an instance field in a static block
class Shop { String name = "Sharma Stores";
static { System.out.println("Opening " + name); }}
public class ShopBlockDemo { public static void main(String[] args) { new Shop(); }}ShopBlockDemo.java:5: error: non-static variable name cannot be referenced from a static context
System.out.println("Opening " + name);
^
1 errorWhat this code does
- A static block runs once for the class, with no object, so it cannot know whose
nameto use. - Fix: make
namestatic if it is one value for the class, or print it in the constructor instead.
It is the same static context error as in static methods (opens in a new tab). Keep static blocks short: setup that needs a loop or several steps, nothing more.
Find the bug
Find the setup mistake
Select the line that is wrong.
"Loading fares" should print once, not once per ticket.
Round 1 of 3Next step
Check your understanding
12 quick questions