Java Reference ยท Object-Oriented Concepts
Immutable classes in Java
How to design immutable classes in Java: final fields, defensive copies, no setters, records, unmodifiable collections, and the benefits for thread safety.
An immutable object cannot change after it is constructed. String, the wrapper classes, BigDecimal, LocalDate and records of immutable parts are all immutable. Immutability makes objects safe to share between threads without locking, safe to use as map keys, and easy to reason about, because nobody can alter a value behind your back.
Java has no keyword that makes a class immutable. You get there by following a set of design rules, then the compiler and the memory model help you: final fields are safely published, so other threads see the fully built object.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
The rules
- Declare the class
final(or make every constructor private and use factories) so a subclass cannot add mutable state. - Make every field
private final. - Provide no setters or other methods that change state. Methods that "modify" return a new object instead.
- Initialize all fields in the constructor.
- Copy mutable inputs on the way in and mutable outputs on the way out ("defensive copies").
List.copyOf,Map.copyOf,Set.copyOfandArrays.copyOfhelp. - Do not let
thisescape from the constructor, for example by registering it in a listener list before the fields are set.
Records follow most of this automatically: fields are private and final, there are no setters, and the class is implicitly final. They are only as immutable as their components, which is why the compact constructor above copies the list.
Usage notes
- Shallow vs. deep:
finalprotects the reference, not the object behind it. Afinal List<String>can still receiveaddunless the list is unmodifiable. Collections.unmodifiableList(list)is a view, not a copy: changes to the original list show through.List.copyOftakes a snapshot.List.of,Set.of,Map.ofare immutable but rejectnullelements;Collections.unmodifiableListallows them.- Thread safety is free: immutable objects need no synchronization, and a
finalfield is guaranteed visible after construction. - Cost: every change creates a new object. For heavy edits use a mutable builder (like
StringBuilder) and produce the immutable result once, see the builder pattern. - Cache friendly: hash codes can be cached and instances can be shared (flyweights,
Integer.valueOfcache). - Arrays are always mutable. Never expose an internal array; return a copy or a list view.
- Dates and times: prefer
java.timetypes overjava.util.Date, which is mutable. - Serialization and frameworks sometimes want setters or a no-arg constructor; records and constructor binding avoid the compromise.