Java Immutable Objects and Defensive Copies (OCP 21)
Writing immutable classes in Java for the OCP 21 exam: the five-step recipe, why final fields aren't enough, defensive copies in constructors and accessors, List.copyOf versus unmodifiable views, arrays, and how records fit in.
kvi5hnuCode Sprout team member7 min readOn this page
An immutable object can't change state after it has been constructed. String, the wrapper classes and every java.time type are immutable, and the exam expects you to know how to write such classes yourself. It also expects you to spot classes that only look immutable.
Immutable objects pay off because:
- they can be shared freely, including between threads (chapter 13), with no locking
- they can't be put into an invalid state after construction, which suits security-sensitive values
- they make safe keys in maps and elements in sets, because their hash code never changes
The recipe
A common strategy has five steps:
- Prevent subclassing. Mark the class
final, or make every constructorprivateand offer static factory methods. - Make all instance fields
privateandfinal. - Write no setters, and no other methods that change fields.
- Never let callers reach a mutable object the class holds. Don't return it directly from a getter.
- Set every field in a constructor, and copy any mutable argument instead of storing the caller's reference.
Each step closes a different door:
- Step 1 stops someone from writing a mutable subclass. A subclass could add mutable fields or override getters, and then pass itself off as the "immutable" parent type.
- Steps 2 and 3 stop direct changes.
- Steps 4 and 5 stop changes through shared references. These two are the steps people forget.
Why private final isn't enough
final stops a field from being reassigned. It doesn't stop the object the field points to from being changed:
public final class Garden { // steps 1, 2 and 3 followed
private final List<String> plants;
public Garden(List<String> plants) { this.plants = plants; }
public List<String> getPlants() { return plants; }
}
var mine = new ArrayList<>(List.of("fern"));
var g = new Garden(mine);
mine.add("weed"); // door 1: the caller kept a reference
g.getPlants().clear(); // door 2: the getter handed out the internal list
Both lines change g after it was built. The same applies to a final int[] field, because array elements can always be reassigned.

Closing the doors: defensive copies
A defensive copy is a copy made at the border of the class, so that outside code never shares a mutable object with it.
On the way in (step 5), copy the argument in the constructor:
public Garden(List<String> plants) {
this.plants = new ArrayList<>(plants); // classic approach: a private mutable copy
}
On the way out (step 4), there are three choices:
public List<String> getPlants() { return new ArrayList<>(plants); } // copy on every read
public int plantCount() { return plants.size(); } // or expose only what callers need
public String plant(int i) { return plants.get(i); } // (delegating methods)
Copying on every read is safe but costs an allocation per call. Delegating methods avoid the copy, but every question callers might ask needs its own method.
The modern approach: List.copyOf
Since Java 10, List.copyOf, Set.copyOf and Map.copyOf return unmodifiable copies. Storing one closes both doors at once. Callers can't change their original to affect it, and the getter can return it directly, because any add, remove or clear throws UnsupportedOperationException:
public Garden(List<String> plants) {
this.plants = List.copyOf(plants); // independent and unmodifiable
}
public List<String> getPlants() { return plants; } // safe to return as-is
copyOf doesn't make a new copy if its argument was itself created by List.of or List.copyOf, so repeated calls cost nothing. A Collections.unmodifiableList view is copied, which is exactly what you want. It rejects null: a null list or a null element throws NullPointerException.
| Expression | Independent of the source? | Can callers modify it? | Nulls allowed? |
|---|---|---|---|
new ArrayList<>(src) | yes | yes (it's a normal list) | yes |
Collections.unmodifiableList(src) | no, it's a view | no, but the source can be changed | yes |
List.copyOf(src) | yes | no | no |
List.of(a, b) | (built from values) | no | no |
Copy first, then validate
If the constructor checks an invariant, such as "at least one plant", check the copy, not the argument. Another thread could change the argument between your check and your copy:
public Garden(List<String> plants) {
List<String> safe = List.copyOf(plants); // copy first
if (safe.isEmpty()) throw new IllegalArgumentException("need at least one plant");
this.plants = safe;
}
Arrays and other mutable types
Arrays are always mutable, so copy them both ways with clone() or Arrays.copyOf. Note that clone() is shallow. For an int[][], the inner arrays are still shared.
Fields whose types are already immutable need no copy. That includes String, Integer, LocalDate, BigDecimal (article 22) and other immutable classes. Legacy mutable types such as java.util.Date do need copying, which is one reason modern code uses java.time instead.
"Changing" an immutable object
When the state needs to change, return a new object. This is the style of String.concat and LocalDate.plusDays:
public Garden withPlant(String p) {
var more = new ArrayList<>(plants);
more.add(p);
return new Garden(more); // the constructor copies again
}
Methods named withX are the common convention for this.
Records
Records (chapter 7) give you steps 1 to 3 for free. A record is implicitly final, its fields are private final, and it has no setters. They don't give you steps 4 and 5. A record holding a List stores whatever list was passed in, so it's only shallowly immutable:
record Team(String name, List<String> members) { } // members can still change
record SafeTeam(String name, List<String> members) {
SafeTeam { members = List.copyOf(members); } // compact constructor makes the copy
}
The compact-constructor form is explained in the records article. In modern code, a record with List.copyOf in its compact constructor is the usual way to write an immutable data carrier.
What's current
- Records (Java 16, article 41) are the current way to write simple immutable data carriers. The defensive-copy rules here still apply to their mutable components.
List.of,Set.of,Map.of(Java 9) andList.copyOf(Java 10) give unmodifiable collections for defensive copies, and Java 16 addedStream.toList().- Java 25 previews stable values (
StableValue, JEP 502) for lazily set constants. It's a preview API and isn't on either exam.
Exam traps from this article
A complete example
The program builds a "leaky" playlist that follows only steps 1 to 3, then an immutable playlist that also copies at its borders, and tries the same tampering on both.
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
// Looks immutable, but leaks its mutable internals
static final class LeakyPlaylist {
private final String name;
private final List<String> songs;
LeakyPlaylist(String name, List<String> songs) {
this.name = name;
this.songs = songs; // stores the caller's list
}
List<String> songs() { return songs; } // hands out the internal list
String name() { return name; }
}
// Immutable: final class, private final fields, no setters, copies in and out
static final class Playlist {
private final String name;
private final List<String> songs; // unmodifiable copy
private final int[] ratings; // arrays are always mutable: copy them
private final LocalDate created; // LocalDate is already immutable
Playlist(String name, List<String> songs, int[] ratings, LocalDate created) {
List<String> safeSongs = List.copyOf(songs); // copy first...
if (safeSongs.isEmpty()) { // ...then validate the copy
throw new IllegalArgumentException("a playlist needs at least one song");
}
this.name = name;
this.songs = safeSongs;
this.ratings = ratings.clone();
this.created = created;
}
String name() { return name; }
List<String> songs() { return songs; } // safe: unmodifiable
int[] ratings() { return ratings.clone(); } // copy on the way out
LocalDate created() { return created; }
// "Modifying" returns a new object instead
Playlist withSong(String song, int rating) {
List<String> more = new ArrayList<>(songs);
more.add(song);
int[] moreRatings = Arrays.copyOf(ratings, ratings.length + 1);
moreRatings[ratings.length] = rating;
return new Playlist(name, more, moreRatings, created);
}
@Override
public String toString() {
return name + " " + songs + " " + Arrays.toString(ratings) + " " + created;
}
}
public static void main(String[] args) {
List<String> mine = new ArrayList<>(List.of("Intro", "Rain"));
LeakyPlaylist leaky = new LeakyPlaylist("Leaky", mine);
mine.add("Sneaked in"); // changes the "final" object
System.out.println("Leaky, caller's list changed: " + leaky.songs());
leaky.songs().clear(); // and so does the getter
System.out.println("Leaky, getter result cleared: " + leaky.songs());
mine = new ArrayList<>(List.of("Intro", "Rain"));
int[] stars = {4, 5};
Playlist safe = new Playlist("Safe", mine, stars, LocalDate.of(2026, 3, 1));
mine.add("Sneaked in");
stars[0] = 1;
safe.ratings()[1] = 0;
try {
safe.songs().clear();
} catch (UnsupportedOperationException e) {
System.out.println("songs().clear() -> UnsupportedOperationException");
}
System.out.println("Safe after tampering: " + safe);
Playlist longer = safe.withSong("Outro", 3);
System.out.println("withSong result: " + longer);
System.out.println("original unchanged: " + safe);
try {
new Playlist("Empty", List.of(), new int[0], LocalDate.of(2026, 3, 1));
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Output:
Leaky, caller's list changed: [Intro, Rain, Sneaked in]
Leaky, getter result cleared: []
songs().clear() -> UnsupportedOperationException
Safe after tampering: Safe [Intro, Rain] [4, 5] 2026-03-01
withSong result: Safe [Intro, Rain, Outro] [4, 5, 3] 2026-03-01
original unchanged: Safe [Intro, Rain] [4, 5] 2026-03-01
Rejected: a playlist needs at least one song
Points to notice:
- The leaky class has
private finalfields and no setters, yet the caller changes it twice: once through its own list, and once through the getter. Playlistcopies the list withList.copyOfand the array withclone(). Afterwards, changingmineorstarshas no effect.songs()returns the stored unmodifiable list, soclear()throws.ratings()returns a fresh clone, so writing to it changes nothing inside.withSongbuilds a new playlist, and the original stays the same.- The empty-list check runs on the copy, after copying.
Common questions
Do I need final on the class if all constructors are private?
Not strictly. With only private constructors, no outside class can extend it. Nested classes still could, though, so final is the clearer choice. The book-style recipe accepts either option.
Is a class with no fields immutable? Yes, trivially, as long as it isn't extensible in a way that adds state.
Should getters of immutable classes return copies of String fields?
No. String is immutable, so returning the field directly is safe.
What about collections of mutable objects?
List.copyOf copies the list, not its elements. For deep immutability, the elements themselves must be immutable, or you must copy them too.
Summary
- Immutable means no state change after construction. Make the class
final(or give it private constructors), make the fieldsprivate final, and write no setters. finalfields can still point to mutable objects. Copy mutable inputs in the constructor and never hand out internal mutable objects.List.copyOfand related methods give independent, unmodifiable copies (no nulls).Collections.unmodifiableListis just a view.- Validate the copy, not the argument. Return new objects (
withX) instead of mutating. - Records automate the first three steps. Add
List.copyOfin a compact constructor for the rest.
Practice quiz
Test yourself with the immutable objects quiz: 10 exam-style questions with explanations.
You've finished Chapter 6. Check your understanding of the whole chapter with the Chapter 6 review quiz: 20 mixed questions on inheritance, constructors, initialization order, overriding, abstract classes and immutability.
Previous: Java Abstract Classes and Abstract Methods (OCP 21)
Next: Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
Related reading
- Java Abstract Classes and Abstract Methods (OCP 21)
- Java Method Overriding and Hiding: Rules, final Methods and Static Hiding (OCP 21)
- Java Initialization Order and final Fields (OCP 21)
- Java Constructors: Default Constructor, this() and super() (OCP 21)
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.