Immutable Classes in Java: How to Create an Immutable Object
An immutable object is an object whose state cannot change after it is created. String, Integer, LocalDate and BigDecimal all work this way. To make your own class immutable, follow five rules: declare the class final, make every field private final, write no setters, copy mutable constructor arguments, and never hand out references to mutable internal objects.
The last two rules are the ones people forget. The class below is final, both fields are final, there are no setters, and yet the object still changes, in two different ways:
public final class Employee {
private final String name;
private final List<String> skills;
public Employee(String name, List<String> skills) {
this.name = name;
this.skills = skills; // keeps the caller's reference
}
public String getName() { return name; }
public List<String> getSkills() { return skills; } // hands out its own reference
}
List<String> skills = new ArrayList<>(List.of("Java"));
Employee e = new Employee("Anna", skills);
skills.add("COBOL"); // change the list from outside
System.out.println(e.getSkills()); // [Java, COBOL]
e.getSkills().clear(); // change it through the getter
System.out.println(e.getSkills()); // [] final stops a field from being reassigned, but it does not stop anyone from changing the object the field points to. The sections below close both holes step by step. Each rule comes with the code that breaks without it.
What an immutable object is and why it matters
An immutable object receives all its values in the constructor and never changes them afterwards. No method of the class modifies a field, and calling code has no way to reach the internal state. Methods that look like modifications actually return a new object. String.toUpperCase() works this way: the original string stays the same. String immutability has its own lesson.
The restriction pays off because the object becomes predictable:
| Property | What it gives you in practice |
|---|---|
| Thread safety without synchronization | You can share the object with any number of threads, and none of them can corrupt it. More in the thread safety lesson. |
Safe HashMap keys and HashSet elements | hashCode() never changes, so an entry is never "lost" inside the collection. |
| Free passing to methods | A method you pass the object to cannot damage it, so no defensive copies are needed. See passing objects to methods. |
| Caching and reuse | One instance can be shared by everyone. That is how the string pool and the Integer.valueOf() cache for -128 to 127 work. |
| Invariants are checked once | If the constructor checked that the start date is before the end date, that stays true for the object's whole life. |
There is one cost: every "change" creates a new object. For small values such as money, dates and coordinates this is almost free. When you build a string out of thousands of pieces in a loop, use a mutable companion such as StringBuilder.
The five rules of an immutable class
A class is immutable only when all five rules hold. If even one is broken, the object's state can be changed behind its methods' back.
- The class is
final(or has onlyprivateconstructors and static factories). - All fields are
private final. - There are no setters or other methods that change fields.
- Mutable constructor arguments are copied: a
List, an array, aDate. - Methods never return references to mutable internal objects, only a copy or an unmodifiable view.
| Rule | What breaks without it | Section |
|---|---|---|
final class | A subclass overrides a getter and fakes the value of an object that looks immutable | Why final |
private fields | Outside code reads the field directly and changes its contents if they are mutable | Access modifiers |
final fields | A method of the class can reassign a field by accident. With final the compiler refuses | final variables |
| No setters | The object changes through its own public API | with-methods |
| Copy on the way in | The caller keeps a reference to its list and changes it after the object is created | Copies in the constructor |
| Copy on the way out | Anyone who calls the getter gets a reference to the internal state | Copies in getters |
If every field is a primitive or an already immutable type (String, Integer, LocalDate), rules 4 and 5 hold by themselves because there is nothing to copy. That is why the easiest way to design an immutable class is to build it from immutable parts.
Step by step: from a mutable class to an immutable one
Start with an ordinary JavaBeans-style class: private fields, getters and setters.
public class Employee {
private String name;
private int salary;
private List<String> skills;
public Employee(String name, int salary, List<String> skills) {
this.name = name;
this.salary = salary;
this.skills = skills;
}
public String getName() { return name; }
public int getSalary() { return salary; }
public List<String> getSkills() { return skills; }
public void setSalary(int salary) { this.salary = salary; }
public void setSkills(List<String> skills) { this.skills = skills; }
} Making it immutable takes five edits, one per rule:
import java.util.List;
import java.util.Objects;
public final class Employee { // 1. final class
private final String name; // 2. private final fields
private final int salary;
private final List<String> skills;
public Employee(String name, int salary, List<String> skills) {
this.name = Objects.requireNonNull(name);
if (salary < 0) {
throw new IllegalArgumentException("salary < 0: " + salary);
}
this.salary = salary;
this.skills = List.copyOf(skills); // 4. copy on the way in
}
public String getName() { return name; }
public int getSalary() { return salary; }
public List<String> getSkills() { return skills; } // 5. List.copyOf is already unmodifiable
public Employee withSalary(int newSalary) { // 3. instead of a setter
return new Employee(name, newSalary, skills);
}
} Here is what happens now to the code that broke the object at the start of the lesson:
List<String> skills = new ArrayList<>(List.of("Java"));
Employee e = new Employee("Anna", 1000, skills);
skills.add("COBOL");
System.out.println(e.getSkills()); // [Java]
e.getSkills().clear(); // java.lang.UnsupportedOperationException The getter returns the internal field without copying it, and that is safe: List.copyOf() creates an unmodifiable list that nobody can change, including the class itself. If you store a plain ArrayList instead, every getter has to make a copy. That case is covered in copies in getters.
Put validation and Objects.requireNonNull() in the constructor. An immutable object has no other place where it could become valid: if the constructor lets a negative salary through, the object keeps it forever.
Defensive copies in the constructor
A defensive copy is a copy of a mutable argument that the constructor stores instead of the reference the caller passed. After that, the caller can change the original however it likes: our instance no longer depends on it.
The order matters: copy first, then validate. Take a booking with two java.util.Date values, which is a mutable class:
public final class Booking {
private final Date from;
private final Date to;
public Booking(Date from, Date to) {
this.from = new Date(from.getTime()); // copy first
this.to = new Date(to.getTime());
if (this.from.after(this.to)) { // then validate the copies
throw new IllegalArgumentException(this.from + " is after " + this.to);
}
}
public Date getFrom() { return new Date(from.getTime()); }
public Date getTo() { return new Date(to.getTime()); }
} If you validate the originals and copy afterwards, there is a window between the check and the copy. Another thread that holds a reference to the same Date can move the date during that window, and the object ends up storing values that never passed the check. When you validate the copies, nobody but the constructor can see them.
One more detail: the copy uses new Date(from.getTime()), not from.clone(). Date is not final, so the caller can pass a subclass whose overridden clone() returns anything at all. The constructor does not allow that substitution. Better still, avoid mutable types entirely: if the fields are LocalDate or Instant, no copies are needed because those classes are immutable. See the LocalDate lesson.
| Argument type | How to copy it in the constructor |
|---|---|
List, Set, Map | List.copyOf(list), Set.copyOf(set), Map.copyOf(map) (Java 10) |
| Array | array.clone() or Arrays.copyOf(array, array.length) |
Date | new Date(date.getTime()), or better, replace it with Instant or LocalDate |
| Your own mutable class | A copy constructor: new Address(address) |
String, Integer, LocalDate, a record of immutable fields | Nothing to do, store the reference |
Defensive copies in getters
A copy on the way in closes only half the hole. If a getter returns the internal array or ArrayList, the caller gets direct access to the object's state.
public final class Exam {
private final int[] scores;
public Exam(int[] scores) {
this.scores = scores.clone(); // copy on the way in: done
}
public int[] getScoresLeaky() {
return scores; // reference to the internal array
}
public int[] getScores() {
return scores.clone(); // copy on the way out
}
}
Exam exam = new Exam(new int[] {90, 75});
exam.getScoresLeaky()[0] = 0;
System.out.println(Arrays.toString(exam.getScores())); // [0, 75] An array is always mutable and has no unmodifiable view, so every call to the getter must return a fresh copy. With collections you have a choice: store an unmodifiable copy and return it as is (cheaper), or store a mutable one and wrap it on the way out.
// option 1: unmodifiable copy in the field, the getter copies nothing
this.skills = List.copyOf(skills);
public List<String> getSkills() { return skills; }
// option 2: mutable copy in the field, the getter returns a view
this.skills = new ArrayList<>(skills);
public List<String> getSkills() { return Collections.unmodifiableList(skills); } Option 2 is for classes that change the list internally, for example to cache or extend it. That is rare in an immutable class, so option 1 is the usual choice.
List.copyOf, unmodifiableList and other options
The methods that "make a list unmodifiable" behave differently. The key difference is whether they make a copy or only a view on top of the original list.
List<String> src = new ArrayList<>(List.of("a"));
List<String> view = Collections.unmodifiableList(src);
List<String> copy = List.copyOf(src);
src.add("b");
System.out.println(view + " " + copy); // [a, b] [a]
view.add("c"); // java.lang.UnsupportedOperationException Collections.unmodifiableList() forbids changes through itself, but shows every change to the original. If the caller still holds the original list, your "unmodifiable" field changes right in front of you. The wrapper on its own is not a defensive copy: you have to pass it a list you already copied.
| Option | Copy or view | Sees changes to the source | null elements | Java version |
|---|---|---|---|---|
new ArrayList<>(src) | Mutable copy | No | Allowed | 1.2 |
Collections.unmodifiableList(src) | View | Yes | Allowed | 1.2 |
List.copyOf(src) | Unmodifiable copy | No | NullPointerException | 10 |
Collections.unmodifiableList(new ArrayList<>(src)) | Copy in a wrapper | No | Allowed | 1.2 |
src.stream().toList() | Unmodifiable copy | No | Allowed | 16 |
List.copyOf() has a useful optimization: if you pass it a list that is already unmodifiable (the result of List.of() or another copyOf()), it returns the same object without copying. That is why withSalary() above passes skills to the new constructor for free: List.copyOf(skills) == skills is true. Collections.unmodifiableList() cannot do this, because it does not know whether the original list has other owners.
If your data may contain null, List.copyOf() will not work. Use stream().toList() or a copy in a wrapper.
Deep vs shallow immutability
List.copyOf() copies the list, not its elements. If the elements are mutable, the object is only shallowly immutable: you cannot add or remove an element, but you can change the element itself.
class Lesson { // a mutable class
private String title;
Lesson(String title) { this.title = title; }
String getTitle() { return title; }
void setTitle(String title) { this.title = title; }
}
final class Course {
private final List<Lesson> lessons;
Course(List<Lesson> lessons) { this.lessons = List.copyOf(lessons); }
List<Lesson> getLessons() { return lessons; }
}
Lesson lesson = new Lesson("Strings");
Course course = new Course(List.of(lesson));
lesson.setTitle("Changed");
System.out.println(course.getLessons().get(0).getTitle()); // Changed In Course both the list and the field are fine, yet the state still changed through a list element. There are two ways to fix this:
- Make the elements immutable, for example turn
Lessonintorecord Lesson(String title). Then a defensive copy of the list is enough, and this is the best option. - Deep copy: copy every element on the way in and on the way out,
lessons.stream().map(Lesson::new).toList()(this needs a copy constructor). Every getter becomes expensive, and it is easy to miss one spot.
Deep immutability means that every object reachable from the fields is immutable. Only deep immutability gives real guarantees: thread safety, a stable hashCode(), no surprises. That is why immutable classes are usually built from parts that are immutable too.
with-methods instead of setters
When an object cannot change, a "change" is written as a method that returns a new instance with one field set to a different value. Such methods are usually called withXxx(), like LocalDate.withYear(), or named after the operation, like plusDays(), add() in BigDecimal and toUpperCase() in String.
Employee anna = new Employee("Anna", 1000, List.of("Java"));
anna.withSalary(2000); // the result is lost
System.out.println(anna.getSalary()); // 1000
Employee promoted = anna.withSalary(2000);
System.out.println(promoted.getSalary()); // 2000
System.out.println(anna.getSalary()); // 1000: the original did not change The most common mistake with immutable types is calling a method and not keeping the result. The compiler will not catch it. In interviews and on the OCP exam it shows up as s.toUpperCase();, date.plusDays(1); or bd.add(BigDecimal.ONE); with no assignment. When you work with an immutable type, always keep the result of a method that looks like a modification.
Many fields: use a builder
With ten fields, a ten-parameter constructor and ten with methods get awkward. In that case, add a mutable Builder next to the class: you fill it with setters, and its build() method calls the immutable class's constructor once. The StringBuilder → String pair works the same way.
Why the class must be final
Even when every field is private final, a class that is not final can be extended by a mutable subclass. Code that holds a variable of the base type has no way to know the object behaves differently:
class Point { // not final
private final int x;
Point(int x) { this.x = x; }
int getX() { return x; }
}
class MutablePoint extends Point {
private int fakeX;
MutablePoint(int x) { super(x); fakeX = x; }
@Override int getX() { return fakeX; } // fake the value
void setX(int x) { fakeX = x; }
}
Point p = new MutablePoint(1);
System.out.println(p.getX()); // 1
((MutablePoint) p).setX(5);
System.out.println(p.getX()); // 5 The object's x field is still 1, but anyone working with Point sees 5. There are two ways to forbid inheritance:
- declare the class
final(see final classes). Trying to extend it fails withcannot inherit from final Point; - make every constructor
privateand create objects through a static factory,Point.of(1). A subclass cannot callsuper(...), and the factory can also cache common values the wayInteger.valueOf()does.
There is a historical example of this rule being broken: BigInteger and BigDecimal are not final. A method that accepts a BigInteger from untrusted code and relies on its immutability has to check the exact class or make a copy: new BigInteger(arg.toByteArray()). String, the wrapper classes and the java.time classes do not have this problem because they are final.
A record as an immutable class
A record (Java 16) satisfies three of the five rules automatically: it is implicitly final, its fields are private final, and it has no setters. Defensive copies are still your job. Here is the immutable Employee as a record:
public record Employee(String name, int salary, List<String> skills) {
public Employee { // compact constructor
Objects.requireNonNull(name);
if (salary < 0) {
throw new IllegalArgumentException("salary < 0: " + salary);
}
skills = List.copyOf(skills); // defensive copy
}
public Employee withSalary(int newSalary) {
return new Employee(name, newSalary, skills);
}
}
Employee e = new Employee("Anna", 1000, new ArrayList<>(List.of("Java")));
Employee e2 = e.withSalary(2000);
System.out.println(e2); // Employee[name=Anna, salary=2000, skills=[Java]]
System.out.println(e2.skills() == e.skills()); // true: the list was not copied again The compiler generated the accessors, equals(), hashCode() and toString(). A regular class would have to write them (see the equals() method). An array component is something a record cannot handle on its own: the accessor returns the internal array, and equals() compares arrays by reference. That case is covered in records and immutability.
You need a regular class instead of a record when you want to hide some fields from the API, keep a cache (for example a hashCode computed once, as String does), or extend another class.
Immutable and mutable classes in the JDK
Many mutable JDK classes have an immutable replacement. A field of an immutable type needs no defensive copy.
| Immutable | Mutable counterparts |
|---|---|
String | StringBuilder, StringBuffer, char[] |
Integer, Long, Double and the other wrapper classes | AtomicInteger, AtomicLong, int[] |
BigInteger, BigDecimal (but not final) | — |
LocalDate, LocalDateTime, Instant, Duration, ZonedDateTime | Date, Calendar, java.sql.Timestamp |
List.of(), Set.of(), Map.of(), List.copyOf() | ArrayList, HashSet, HashMap |
Optional, UUID, Path, Pattern, enum | — |
An enum is immutable only as long as you add no mutable fields to it: the compiler does not stop you from declaring a regular field with a setter in an enum. A collection from List.of() is also only shallowly immutable: List.of(new StringBuilder("a")) will not let you add an element, but get(0).append("b") works.
Does it compile? OCP-style questions
Exam questions about immutability check whether you understand the difference between a final reference and an immutable object, and whether you know which mistakes the compiler catches and which appear only at run time.
| Code | Result |
|---|---|
final List<String> list = new ArrayList<>(); list.add("x"); | Compiles and runs: final forbids reassigning the reference, not changing the list |
private final int x; and a method void setX(int x) { this.x = x; } | Compile error: cannot assign a value to final variable x |
private final int x;, constructors A(int x) { this.x = x; } and A() { } | Compile error in the second constructor: variable x might not have been initialized |
final class C { } and class D extends C { } | Compile error: cannot inherit from final C |
List.of("a").add("b"); | Compiles, throws UnsupportedOperationException at run time |
List.copyOf(Arrays.asList("a", null)); | Compiles, throws NullPointerException at run time |
String s = "java"; s.toUpperCase(); System.out.println(s); | Prints java: the method's result was not kept |
Notice that none of the collection immutability checks happen at compile time. The type of List.of() is still List<String>, and it has an add() method. Only running the code reveals the error.
Frequently asked questions
Can a final field be changed with reflection?
In a regular class, yes: after field.setAccessible(true), calling field.setInt(obj, 42) overwrites a private final field, and JDK 25 says nothing. For records and hidden classes the same call throws IllegalAccessException. In JDK 26 (JEP 500), writing to final fields through reflection prints a warning by default, and later releases plan to forbid it. Immutability protects against bugs in code, not against someone who breaks encapsulation on purpose.
What is the difference between an unmodifiable collection and an immutable object?
An unmodifiable collection (List.of(), List.copyOf()) forbids adding, removing and replacing elements, but anyone can change the elements themselves if they are mutable. An immutable object in the strict sense never changes as a whole, including everything it references. A list of strings is deeply immutable; a list of StringBuilder is only shallowly immutable.
How is Lombok @Value different from a record?
@Value generates a regular class: it makes it final, makes the fields private final, and adds getX() getters, a constructor and equals()/hashCode()/toString(). It works on Java 8 and lets you hide individual fields. Neither a record nor @Value makes defensive copies. On Java 16 and later a record is usually the better choice because it needs no third-party library.
When is immutability a bad fit?
When an object changes often and as a whole: a buffer filled in a loop, a game board, or a large matrix in a computation. Creating a new object for every change is expensive there, so you use a mutable class and keep it inside one method or one thread. JPA and Hibernate entities are another exception: the framework needs a no-argument constructor and mutable fields.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
All module tasks →
Comments