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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
finalon 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
Dateis mutable. - Fix: copy in and protect out.
List.copyOf(items)makes an unmodifiable independent copy and rejects nulls. UseInstantinstead ofDate. Collections.unmodifiableListis only a read-only view: changes to the original list show through.List.copyOfis 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
- What makes a class immutable?
- This Order class has final fields. Is it immutable? Find the leaks.
- What is the difference between
Collections.unmodifiableListandList.copyOf? - Why do immutable objects make good map keys?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.