Order of Initialization: Fields Before Constructor Body
What You'll Learn
You'll learn the exact sequence Java follows when creating an object: field initializers always execute before any constructor body code runs.
The Initialization Timeline
When you create an object with new, Java follows a strict order of operations. Field initializers execute first, then the constructor body runs. This happens every single time, no exceptions.
Think of it like building a house: Java lays the foundation (initializes fields) before the construction crew (constructor body) starts their work.
The Two-Step Process
Step 1: Field initialization
- All fields with explicit initializers are set
- Fields without initializers get their default values (0, false, null)
Step 2: Constructor body
- The code inside your constructor's curly braces executes
- This can read or modify the already-initialized fields
Practical Example
public class Account {
private double balance = 100.0; // Step 1: Set to 100.0
private String owner; // Step 1: Set to null
public Account(String name) {
// Step 2: Constructor body runs AFTER fields are set
System.out.println("Balance is: " + balance); // Prints 100.0
this.owner = name; // Can now modify the field
}
}
When you call new Account("Alice"), here's what happens in order:
balancebecomes100.0ownerbecomesnull- Constructor prints "Balance is: 100.0"
owneris reassigned to "Alice"
This matters when your constructor logic depends on field values, or when you're debugging initialization issues.
Key Takeaway: Field initializers always execute before the constructor body, establishing initial state before your constructor code runs.