class Tracker {
static int instances = 0;
static {
instances = 100;
}
int id;
{
id = ++instances;
}
Tracker() {
System.out.println("id=" + id + ", total=" + instances);
}
}
new Tracker();
new Tracker();
What prints? The answer depends on when each block runs relative to the others. This article explains the sequence.
Two categories of initialization
Java splits initialization into two categories: class initialization and instance initialization.
Class initialization happens once per class, the first time the JVM uses it. It runs static field initializers and static initializer blocks in textual order.
Instance initialization happens once per object, every time new is called. It runs instance field initializers, instance initializer blocks, and the constructor body.
The two categories never overlap for the same execution. Static code runs before any instance is created. Instance code runs after static code has already finished.
Class initialization
The JVM initializes a class the first time it is actively used: when an instance is created, a static method is called, a static field is accessed, or the class appears as the left-hand side of an assignment. It does not initialize a class just because the classloader found it.
During class initialization, static field initializers and static { } blocks run in textual order:
class Config {
static int maxConnections = 10; // runs first
static {
System.out.println("class loaded"); // runs second
maxConnections = 20; // overwrites the field initializer
}
static int timeout = maxConnections * 2; // runs third, sees 20
}
After this class initializes: maxConnections is 20, timeout is 40.
Class initialization happens exactly once. If two threads try to initialize the same class simultaneously, the JVM serializes them: the second thread waits until the first finishes. This is a language guarantee (JLS §12.4.2).
Instance initialization
When new creates an object, the JVM runs three things in order:
- The superclass constructor (covered below under
super()) - Instance field initializers and instance initializer blocks, in textual order
- The rest of the constructor body
An instance initializer is a bare { } block inside the class body but outside any method or constructor. It is copied into every constructor by the compiler, after any super() call and before the constructor's own statements.
class Counter {
int count = 0; // field initializer
{
count = 10; // instance initializer — overwrites 0
}
Counter() {
count = 20; // constructor body — overwrites 10
}
}
After new Counter(): count is 20. The field initializer sets 0, the instance initializer overwrites with 10, then the constructor body overwrites with 20.
That example is contrived. You would not normally use all three. Instance initializers are useful when you want shared setup code across multiple constructors without calling a helper method, or when initializing an anonymous class.
Constructor chaining with this()
Classes, fields, and constructors introduced the this(...) call. When a constructor starts with this(args), it delegates immediately to another constructor in the same class. That constructor runs first. When it returns, nothing else in the calling constructor runs before it. The this() call must be the first statement.
class Account {
String id;
int balance;
boolean active;
Account(String id) {
this(id, 0); // calls Account(String, int) first
// this line runs after Account(String, int) returns
}
Account(String id, int balance) {
this.id = id;
this.balance = balance;
this.active = true;
}
}
The chain terminates at a constructor that does not start with this(). That terminal constructor is responsible for calling super().
You cannot have both this() and super() in the same constructor. this() transfers the obligation to call super() to the constructor it delegates to.
super() and the constructor chain up the hierarchy
Every constructor either starts with this(args) or starts with super(args). If you write neither, the compiler inserts super() automatically.
super() invokes the superclass constructor. Because every class extends Object (explicitly or implicitly), every constructor chain eventually calls Object(). The superclass constructor runs before the subclass's instance initializers and constructor body.
For a class hierarchy A extends Object, B extends A, the sequence when calling new B() is:
-
B()'s first statement issuper()(explicit or implicit), soA()runs first -
A()'s first statement issuper(), soObject()runs first -
Object()returns -
A()'s instance initializers and field initializers run (in textual order) -
A()'s constructor body runs -
A()returns -
B()'s instance initializers and field initializers run -
B()'s constructor body runs
class Animal {
String type;
Animal(String type) {
this.type = type;
System.out.println("Animal: " + type);
}
}
class Dog extends Animal {
String name;
Dog(String name) {
super("dog"); // must come first
this.name = name;
System.out.println("Dog: " + name);
}
}
new Dog("Rex");
Output:
Animal: dog
Dog: Rex
The superclass constructor finishes before the subclass constructor continues. this.name = name does not run until after Animal(String) has returned.
If a superclass has no no-argument constructor, every subclass constructor must include an explicit super(args) call. The compiler cannot generate one, because it doesn't know what arguments to pass.
The full sequence
Putting it together, here is the complete sequence for new Tracker() from the opening:
- The
Trackerclass has not been used yet, so class initialization runs first:-
static int instances = 0runs (instances = 0) -
static { instances = 100; }runs (instances = 100)
-
- Instance creation for the first
new Tracker():- Memory is allocated;
idis set to its default value 0 -
super()runs (Object's constructor, which does nothing visible) - Instance field initializers and instance initializers run in textual order:
-
int idhas no explicit initializer; it was already 0 from the default -
{ id = ++instances; }runs:instancesbecomes 101,idis set to 101 - Constructor body:
System.out.println("id=101, total=101")
- Memory is allocated;
- Instance creation for the second
new Tracker():- Class initialization does not repeat
- Memory allocated,
iddefaults to 0 -
super()runs -
{ id = ++instances; }runs:instancesbecomes 102,idis 102 - Constructor body:
System.out.println("id=102, total=102")
The output is:
id=101, total=101
id=102, total=102
A caution on calling overridable methods from constructors
The initialization sequence explains a classic trap. A superclass constructor runs before the subclass's instance initializers, so subclass fields are still at their default values when the superclass constructor body executes. If the superclass constructor calls a method that is overridden in the subclass, and that override reads a subclass field, it reads the default value, not the initialized value.
class Base {
Base() {
printValue(); // calls the overridden version
}
void printValue() {
System.out.println("Base");
}
}
class Child extends Base {
int value = 42;
@Override
void printValue() {
System.out.println(value); // value is 0 here, not 42
}
}
new Child(); // prints 0
value = 42 has not run yet when Base() calls printValue(). It runs after Base() returns. Keep constructors simple: assign fields, validate arguments, call this() or super(), but avoid calling overridable methods from a constructor.
Prediction exercise
class Widget {
static int count = 0;
int serial;
static {
count = 10;
}
{
serial = ++count;
}
Widget() {}
Widget(int serial) {
this();
this.serial = serial;
}
}
Widget a = new Widget();
Widget b = new Widget(99);
System.out.println(a.serial + " / " + b.serial + " / " + Widget.count);
Predict the output. Consider: when does the static block run, what does the instance initializer do in each case, and how does this() in the second constructor affect the order?

Top comments (0)