Skip to the page

Types, errors and modern syntax · core

Immutable classes

An immutable class has final fields that point to immutable data. Copy mutable inputs in and protect them out, or the object can still change.

The notes

What you must know

  • final on a field stops reassignment only. The object it points to can still change.
  • Three leaks: the constructor keeps the caller's list, the getter returns the same list, and Date is mutable.
  • Fix: copy in and protect out. List.copyOf(items) makes an unmodifiable independent copy and rejects nulls. Use Instant instead of Date.
  • Collections.unmodifiableList is only a read-only view: changes to the original list show through. List.copyOf is an independent copy.
  • Records are only shallowly immutable. Copy collections in a compact constructor: items = List.copyOf(items).
  • Why immutable: safe to share between threads without locks, safe as map keys, easy to cache and to reason about. String is immutable for the same reasons and for the string pool.
  • Reflection can still change final fields today. JDK 26 warns when that happens, and a future release will deny it by default.

The red pen

Common traps: mistake → fix

  • Mistake: A class with all final fields is immutable

    Fix: not if a field points to a mutable list or Date.

  • Mistake: unmodifiableList makes a safe copy

    Fix: it is a view of the original list.

  • Mistake: Records are deeply immutable

    Fix: only the fields are final; the objects inside can change.

Easy to hard

Questions interviewers ask, easy to hard

  1. What makes a class immutable?
  2. This Order class has final fields. Is it immutable? Find the leaks.
  3. What is the difference between Collections.unmodifiableList and List.copyOf?
  4. Why do immutable objects make good map keys?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview