Lesson · Object Initialization & Memory
final: three places, three meanings
15 min readfinal
One keyword, one theme: the compiler removes a later write. Assigned once for variables, exactly once by construction for fields, closed for extension on methods and classes. And the thing it never grants: immutability.
The constant that drifts
A value that must never change has a way of changing anyway:
class Pricing { double vat = 0.20; // 'constant' by intention } order.vat = 0.25; // later, elsewhere, with good intentions
Predict the fix. A comment does not stop assignment, and neither does discipline spread across a codebase. The compiler must know, and one keyword moves the promise from intention to rule: final. The rest of this lesson is the three places it can stand and what each one actually freezes.
Three places, three meanings
final stands in front of four kinds of declaration, always with the same theme: a later write is taken away at compile time.
| Where final stands | What it forbids | Enforced by |
|---|---|---|
| Local variable or parameter | Reassigning it after its first assignment | The compiler |
| Field | A second assignment; it must be assigned exactly once, at the declaration, in an initialiser, or in every constructor | Definite assignment |
| Method | Overriding it in a subclass | The compiler |
| Class | Extending it at all; String, Integer and records are final for this reason | The compiler |
One word, one theme: no later write. Nothing in this table says anything about what the object contains; that distinction is the next section, and it is where most final confusion lives.
What final does not freeze
final freezes the variable, not the value it points at. The slot can never be repointed; the object behind it is exactly as mutable as its class allows.
final List<String> list = new ArrayList<>(); list.add("one"); // fine: the list object mutates list.clear(); // fine // list = otherList; // compile error: the variable is frozen final Person person = new Person("Ada"); person.name = "Grace"; // fine: the object is not frozen // person = new Person("Ada"); // compile error: the binding is frozen
- Frozen: the binding, meaning which object the variable names.
- Not frozen: the object, meaning every mutable field and method behind that binding.
- Immutability is a property of the class: private final fields, no setters, defensive copies. final is step one of that recipe, never the whole thing.
final is about reassignment, not about mutation. A final field pointing at an ArrayList is a frozen address to a fully mutable object, and half of all review comments about 'making it final' are really asking for the other thing.
Locked bindings · mutable objects
final Person p = new Person("Ada");
p = new Person("Grace"); // compile error
p.name = "Grace"; // allowed: object mutates
final List<String> list = new ArrayList<>();
list.add("x"); // allowed: contents mutate
list = List.of("x"); // compile error
Bindings (in the frame)
Heap objects
nothing allocated yet
Verdict
predict first
The keyword freezes something; the question is exactly what.
Two final bindings are about to exist. Predict which of the five statements the compiler refuses, and after each step, check the verdict panel.
Fields: assigned exactly once, definitely
For fields the compiler enforces something stronger than for locals: a final field must be assigned exactly once, on every path, before construction completes.
class Ticket { final int id; // blank final: declared without a value Ticket(int id) { this.id = id; // the one and only assignment } // void reset() { id = 0; } // compile error: a second assignment }
- Blank final:
final int id;defers the value to the constructor. - Every constructor must assign it exactly once. One constructor that forgets fails to compile; so does any constructor that assigns twice.
- The assignment may live at the declaration, in an initialiser block, or in the constructor, on one of those paths only.
- After construction the value is frozen, and the compiler rejects every later write, methods included.
Definite assignment is the compiler doing bookkeeping you would otherwise do in your head: exactly once, on every path, before the object can escape.
final in practice
Where the keyword earns its place in real code:
- Constants:
static final int MAX = 100. A constant with a compile-time value is inlined into callers by javac, which is also why reading it does not trigger the declaring class's initialisation. - Effectively final and lambdas: a local captured by a lambda must be final or effectively final, meaning assigned once and never changed. Capture copies the value, so freezing the variable is what makes the copy honest.
- Fields: final by default, with blank finals for values only the constructor knows. This is the foundation of immutable types and of safe publication across threads.
- Classes and methods: final classes refuse extension (String, Integer, records); final methods refuse overriding, typically to guard invariants or checks.
The lambda rule is the most practical final in daily work: when the compiler complains that a captured variable 'must be final or effectively final', it is telling you a later write would make the captured copy a lie.
The final playbook
Where to write it, in order of how often it matters:
- Values that never change: make them final at the declaration, not as an afterthought. Default to final locals when reading unfamiliar code, because 'cannot be reassigned below' is half of a data-flow analysis already done.
- Fields: final unless there is a reason to vary; blank finals for the values only the constructor knows.
- Real immutability: start from final fields, then finish the recipe with private visibility, no setters, and defensive copies at every boundary.
- Lambda capture errors: find the reassignment, then decide whether the variable should move into the lambda or the lambda should be restructured.
final removes a later write; it never removes mutation. Bindings freeze, objects stay as mutable as their design, and that sentence resolves most of the confusion around the keyword.
final fields are the foundation of safe publication
The memory model gives final fields a special guarantee: once a constructor completes, any thread that sees the object reference sees correctly initialised final fields, even without synchronisation. That is why immutable classes built from final fields are the standard answer for sharing objects across threads, while mutable non-final state carries no such promise.
Interview angles
What does final mean on a field?+
Assigned exactly once, on every path, before construction completes; afterwards the compiler rejects any write, including in methods.
Blank finals defer the assignment to constructors, and definite assignment checks each path. Teams use final fields to make objects immutable from the inside, and to get the memory model's safe-publication guarantee for free.
class Ticket { final int id; Ticket(int id) { this.id = id; } }
Common misconception: That final fields make the whole object immutable. A final field pointing at a mutable object keeps that object fully mutable.
Follow-up: How does safe publication relate to threads?
Is a final List immutable?+
No. The reference is frozen; the list is not. add and clear work, and only reassigning the variable fails.
final List<T> is as mutable as the ArrayList behind it. List.of and List.copyOf produce genuinely immutable lists instead. The distinction matters the moment the list is handed to other code.
final List<String> list = new ArrayList<>(); list.add("x"); // fine // list = other; // compile error
Common misconception: That final propagates into the contents. It never does; it says nothing about elements or their mutability.
Follow-up: What does make an object immutable, then?
Why must lambda captures be effectively final?+
Because the lambda copies the captured value when it is created; a later reassignment could not be reflected, so the compiler forbids the contradiction.
Effectively final means assigned once and never changed, keyword or not. The rule covers locals and parameters; fields are exempt because this is captured, and fields are read through it at call time.
int base = 10; Runnable r = () -> System.out.println(base); // base must never change after this
Common misconception: That lambda capture is by reference. It is by value, which also explains why a captured object can mutate while the captured reference cannot be replaced.
Follow-up: What does that imply about capturing this?
What is a compile-time constant, and why is it special?+
A static final field of primitive or String type with a constant initialiser. javac inlines its value into callers, so reading it does not trigger the declaring class's initialisation.
Inlining has a stale-value consequence: callers compiled against the old value keep it until recompiled, which is why constants in public APIs deserve care. And the inlined read never trips class initialisation, unlike a static final assigned by a method call.
static final int MAX = 100; // inlined into callers static final List<String> NAMES = List.of(); // not a constant: triggers init
Common misconception: That every static final is a compile-time constant. Only the constant-expression ones are.
Follow-up: Where could inlining bite a library author?
When do you make a method or class final?+
A method when subclasses must not change its behaviour; a class when extension was not designed for, as with String, Integer and records.
final classes refuse subclass-based reuse, and the design alternative is composition. The failure modes are symmetrical: an accidentally open class invites broken subclasses, and closing one too early removes legitimate extension. Sealed classes later added a middle ground: extension allowed, but only by an enumerated list.
final class Money { ... } // no subclasses class Base { final void verify() { ... } } // cannot be overridden
Common misconception: That final classes exist for performance. The reasons are design and safety; the performance effect is negligible.
Follow-up: What did sealed classes add to this picture?