Creating Objects in Java: Constructors, Instance Initializers and Order of Initialization (OCP 21)
How objects are created for the OCP Java 21 exam: new and constructors, the default constructor, methods that only look like constructors, reading and writing fields, instance initializer blocks, illegal forward references, the order of initialization and Java 25 flexible constructor bodies.
kvi5hnuCode Sprout team member9 min readOn this page
A Java program does its work through objects, and every object starts life with new. Exam questions often print messages from field initializers, initializer blocks and constructors, then ask for the exact output. To answer those questions you need to know which code runs and in what order. This article covers constructors, fields and instance initializers. The static side of initialization (static fields and static blocks) and the rules for superclass constructors are covered in the class design chapter.
Calling a constructor
An object is an instance of a class. You create one with new, the class name and parentheses:
Ticket t = new Ticket();
There are two parts. Ticket t declares a reference variable that can point to a Ticket. new Ticket() creates the object and returns a reference to it, which is then stored in t. The variable holds a reference, not the object itself. The difference matters when objects are shared and when they become garbage, which a later article covers.
The Ticket() part calls a constructor, a special member that prepares a new object. You declare one like this:
public class Ticket {
public Ticket() {
System.out.println("creating a ticket");
}
}
Two rules identify a constructor:
- Its name is exactly the class name, with the same capitalization.
- It has no return type, not even
void.
The look-alike method
The exam likes this trap:
public class Ticket {
public void Ticket() { } // NOT a constructor
}
It has a return type, so it's an ordinary method that happens to share the class's name. It compiles, but new Ticket() never calls it. You'd have to call it explicitly, as in t.Ticket(). When you see a capitalized method name, check for a return type.
A constructor with a different name than the class, and no return type, doesn't compile at all. The compiler sees a method with a missing return type.
The default constructor
If a class declares no constructor at all, the compiler adds a default constructor. It takes no parameters, has an empty body and has the same access as the class. As soon as you write any constructor yourself, the default one disappears:
public class Seat {
public Seat(int number) { }
}
Seat s = new Seat(); // DOES NOT COMPILE: there is no Seat() any more
Constructors can be overloaded like methods, with different parameter lists. One constructor can call another of the same class with this(...), which must be the first statement. Overloading, this(...) and super(...) get full coverage in the methods and class design chapters.
Reading and writing fields
Fields (instance variables) hold an object's state. Code that has access to a field can read and write it through a reference:
public class Swallow {
int distance; // instance variable
public static void main(String[] args) {
Swallow bird = new Swallow();
bird.distance = 40; // write
System.out.println(bird.distance); // read: 40
}
}
The caller can be in the same class, as here, or in another class, as long as access modifiers allow it. In real code fields are usually private, with methods to read and change them. That's covered with encapsulation.
A field can be given a value where it's declared, and that initializer can use fields declared above it:
public class Name {
String first = "Ada";
String last = "Lovelace";
String full = first + " " + last; // reads two fields, writes a third
}
Fields without an initializer get a default value: 0 for numeric types, false for boolean, '\u0000' for char and null for references. That's true for fields but not for local variables, which have no default (article 6 covers this).
Instance initializer blocks
Any pair of braces forms a code block. A block placed directly inside a class, outside every method and constructor, is an instance initializer. It runs each time an object is created:
public class Lamp { // block 1: the class body
public static void main(String[] args) { // block 2: a method body
{ System.out.println("Switch"); } // block 3: a block inside a method
}
{ System.out.println("Glow"); } // block 4: an instance initializer
}
That's four blocks, and only the last is an instance initializer. Block 3 is an ordinary nested block that runs when main reaches it. Running this program prints only Switch. main is static and never creates a Lamp, so the instance initializer never runs.
Braces must balance and nest properly, or the file doesn't compile. Counting braces is a quick check when a question asks "how many blocks" or "how many initializers".
Instance initializers are uncommon in everyday code, because putting logic in constructors is clearer. They do appear in anonymous classes, which have no constructors, and they're shared by every constructor of a class. On the exam, expect them in order-of-initialization questions.
Order of initialization
When new creates an object, these steps happen:
- Memory is allocated and every field is set to its default value (
0,false,null). - The superclass constructor runs, either an explicit
super(...)or the implicitsuper()that the compiler inserts. For now the superclass isObject, whose constructor does nothing. - Field initializers and instance initializer blocks run once each, top to bottom in the order they appear in the class.
- The rest of the constructor body runs.

Try this one before reading the answer:
public class Robot {
private String name = "R1";
{ System.out.println("block sees " + name); }
public Robot() {
name = "R2";
System.out.println("constructor");
}
public static void main(String[] args) {
Robot robot = new Robot();
System.out.println(robot.name);
}
}
It prints block sees R1, then constructor, then R2. The field initializer runs before the block because it appears first, and the constructor body runs last, so its assignment is the final one.
Constructors that call this(...)
If a constructor begins with this(...), step 3 doesn't happen there. The initializers run in the constructor that the chain ends at, the one that calls super(...) explicitly or implicitly. So they run exactly once per object, however many constructors are chained. The bodies then finish from the innermost constructor outward:
public class Counter {
int n;
{ n++; System.out.println("init n=" + n); }
Counter() {
this(10);
System.out.println("Counter() n=" + n);
}
Counter(int start) {
n += start;
System.out.println("Counter(int) n=" + n);
}
}
new Counter() prints init n=1, Counter(int) n=11, Counter() n=11.
Forward references
Fields and blocks run in file order, so the compiler stops you from reading a field by its simple name before its declaration:
public class Order {
{ System.out.println(total); } // DOES NOT COMPILE: illegal forward reference
int count = total + 1; // DOES NOT COMPILE: illegal forward reference
int total = 5;
}
Two edge cases surprise people:
- Assigning to a field before its declaration is allowed, as in
{ total = 3; }aboveint total = 5;. The value is then overwritten by the field's own initializer when it runs. - Reading through
thisis allowed, as inint count = this.total + 1;. It compiles and sees the default value0, socountbecomes1. That's legal but confusing, so don't write it in real code. Do recognize it on the exam.
final fields
A final instance field must be assigned exactly once, by the time every constructor finishes. It can be assigned in its declaration, in an instance initializer or in each constructor, but in only one of those places. Assigning it in an initializer block and again in a constructor gives variable might already have been assigned. final gets full treatment in the class design chapter.
What's current
- Java 25 finalized flexible constructor bodies (JEP 513), which allow statements before
super(...)orthis(...). On Java 21 the call must be first. - Initializer order (fields and instance initializers top to bottom, then the constructor body) is unchanged.
Exam traps from this article
A complete example
The Ticket class below logs every step: two field initializers, two instance initializer blocks, two chained constructors and a method that only looks like a constructor.
public class Solution {
static class Ticket {
private String event = log("field event", "Concert");
private int seats; // no initializer: stays 0 until assigned
{
log("initializer block 1, seats=" + seats, null);
seats = 2;
}
private final String code = log("field code", "T-" + seats);
{
log("initializer block 2, code=" + code, null);
}
Ticket() {
this("General"); // delegate first; initializers do not run twice
log("Ticket() body", null);
}
Ticket(String section) {
// implicit super() is here, then the fields and blocks above run
log("Ticket(String) body, section=" + section, null);
event = event + " / " + section;
}
// Starts with a capital letter and has a return type: an ordinary method, not a constructor.
void Ticket() {
log("method named Ticket()", null);
}
private static String log(String step, String value) {
System.out.println(" " + step);
return value;
}
@Override
public String toString() {
return event + ", seats=" + seats + ", code=" + code;
}
}
public static void main(String[] args) {
System.out.println("new Ticket():");
Ticket a = new Ticket();
System.out.println(" => " + a);
System.out.println("new Ticket(\"VIP\"):");
Ticket b = new Ticket("VIP");
System.out.println(" => " + b);
System.out.println("calling b.Ticket():");
b.Ticket();
}
}
Output:
new Ticket():
field event
initializer block 1, seats=0
field code
initializer block 2, code=T-2
Ticket(String) body, section=General
Ticket() body
=> Concert / General, seats=2, code=T-2
new Ticket("VIP"):
field event
initializer block 1, seats=0
field code
initializer block 2, code=T-2
Ticket(String) body, section=VIP
=> Concert / VIP, seats=2, code=T-2
calling b.Ticket():
method named Ticket()
Points to notice:
seatsis0inside block 1, because it has no initializer and still holds its default value.codeis computed after block 1 setsseats = 2, so it'sT-2. Moving thecodedeclaration above block 1 would make itT-0.- With
new Ticket(), the initializers run once, beforeTicket(String)'s body, andTicket()'s body runs last. void Ticket()runs only when it's called explicitly.
Common questions
Is a constructor a method?
Not formally. The Java Language Specification treats constructors as a separate kind of member: they aren't inherited, have no return type and run only through new, this(...) or super(...). Many people call them "special methods" informally, and the exam does too.
Does every class have a constructor? Yes. If you don't write one, the compiler adds a no-argument default constructor. Abstract classes have constructors too; they run when a subclass is instantiated. Interfaces don't have constructors.
What runs first, a field initializer or an instance initializer block? Whichever appears first in the file. They're treated as one sequence, in source order, and the whole sequence runs before the rest of the constructor body.
Can an instance initializer throw a checked exception?
Only if every constructor of the class declares that exception in its throws clause, because the initializer's code effectively runs as part of every constructor.
Can I call a method from a field initializer? Yes, and the method runs at that point in the sequence. Be careful: it can see fields declared below that haven't been initialized yet, which still hold default values.
Why is new Ticket() an error when the class declares Ticket(String)?
Because the compiler adds a default constructor only when a class declares no constructors. Add an explicit Ticket() if you need both.
Summary
new ClassName(...)creates an object, runs a constructor and returns a reference.- A constructor has the class's exact name and no return type. A method with the class's name and a return type is just a method.
- If you write no constructor, the compiler adds a no-argument default constructor. Writing any constructor removes it.
- Fields get default values. Initializers can read fields declared above them, but reading one declared below by simple name is an illegal forward reference.
- An instance initializer is a
{ }block directly in the class body. It runs for every new object. - Order: defaults, superclass constructor, field initializers and instance blocks in file order, then the rest of the constructor body. With
this(...), initializers still run once. - Java 25 allows statements before
super(...)andthis(...)(flexible constructor bodies). Java 21 does not.
Practice quiz
Test yourself with the constructors and initialization order quiz: 10 exam-style questions with explanations.
Previous: Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
Next: Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
Related reading
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- OCP Java 21 Exam Guide (1Z0-830): Format, Objectives, Strategy and Study Plan
- OCP Java 21 Course Outline — Study Plan for the 1Z0-830 Exam
- FFM Upcalls, Variadic Functions and errno

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.