Instance Initializer Block
Every new SIM card goes through the same activation steps, whichever plan you choose: register the number, set up voicemail, send a welcome SMS. In Java, if every constructor of a class needs the same setup, you can write it once in an instance initializer block: a bare pair of braces inside the class. It runs for every new object, before the constructor's own code.
A Block That Runs for Every Object
public class Sims {
static class Sim {
static int nextNumber = 9000001;
int number;
String plan;
String status;
{
number = nextNumber++;
status = "ACTIVE";
}
Sim() {
plan = "Prepaid";
}
Sim(String plan) {
this.plan = plan;
}
}
public static void main(String[] args) {
Sim a = new Sim();
Sim b = new Sim("Postpaid");
System.out.println(a.number + " " + a.plan + " " + a.status);
System.out.println(b.number + " " + b.plan + " " + b.status);
}
}9000001 Prepaid ACTIVE
9000002 Postpaid ACTIVEHow it works
- Lines 8 to 11: an instance initializer block is just
{ ... }directly inside the class, with no name and nostatic. - It runs for every new object, whichever constructor is called: both SIMs got a number and an
ACTIVEstatus. - It runs before the constructor body, so each constructor only adds its own part (the plan).
Try it yourself: add a System.out.println to the block and to each constructor. Which line prints first for each object?
Exactly When It Runs
For each new, Java does this (see "Order of Initialization" for the full picture):
- Memory is allocated and fields get default values.
- The parent class's constructor runs (
super(...)). - Field initializers and instance blocks run, in the order they appear in the class.
- The rest of the constructor body runs.
Under the hood, the compiler copies field initializers and instance blocks into every constructor, right after the super(...) call. That's why they run once per object, whichever constructor is used.
Common Mistakes
Confusing it with a static block. { ... } runs per object; static { ... } runs once per class (see "Static Block").
Depending on fields declared later. Blocks and field initializers run top to bottom; a block can't read a field that's declared (and initialized) below it.
Hiding important setup in a block. Readers look in constructors first; a block far up the class is easy to miss.
Practice
- Easy: Add an instance block to a
Ticketclass that setsbookedAtto"2026-11-12"for every ticket, and create tickets with two different constructors. - Harder: Put two instance blocks in a class, one before and one after a field declaration, each printing a message. Predict the order, then run it.
Key Takeaways
Was this tutorial helpful?