AdvancedOOP Concepts · Lesson 14 of 16 · Updated ·
Immutable Classes and Value Objects in Java — final, Defensive Copies, equals/hashCode and Records
"How do you make a class immutable in Java?" is one of the most common Java interview questions, and "Why is String immutable?" is its twin. An immutable object is one whose state cannot change after it is created. If you want a different value, you create a new object. This lesson shows the rules, a real bug that happens when you miss one, and value objects — small immutable classes like Money or Marks that are compared by their contents.
1. You already use immutable objects
String is immutable. Methods that look like they change it actually return a new string:
public class Main {
public static void main(String[] args) {
String name = "asha";
String upper = name.toUpperCase();
name.concat(" verma"); // result ignored — name does not change
System.out.println(name + " | " + upper);
name = name.concat(" verma"); // keep the NEW object instead
System.out.println(name);
}
}
asha | ASHA
asha verma
Integer, LocalDate, BigDecimal and the lists made by List.of(...) are immutable too.
2. Why bother?
| Benefit | Why it happens |
|---|---|
| Thread-safe for free | Nothing can change, so two threads can share the object without locks |
Safe as HashMap keys and in HashSet | The hash code can never change after the object is stored |
| No surprise changes | You can pass the object to any method without worrying that it gets modified |
| Easy to reason about | The object is valid when built and stays valid forever |
The cost: every "change" creates a new object. For most business objects that cost is tiny; for very large data that changes constantly (like a string built in a loop) use a mutable helper such as StringBuilder.
3. The rules for an immutable class
- Make all fields
private final. - Provide no setters or any method that modifies fields.
- Make the class
final(or the constructor private) so a subclass cannot add mutable behaviour. - Validate in the constructor, so an invalid object can never exist.
- Make defensive copies of mutable inputs (like a
Listor an array) in the constructor, and never hand out the internal mutable object.
Rule 5 is the one people forget. Here is what goes wrong:
import java.util.*;
final class Marksheet {
private final String student;
private final List<Integer> marks;
Marksheet(String student, List<Integer> marks) {
this.student = student;
this.marks = marks; // BUG: stores the caller's list
}
List<Integer> getMarks() { return marks; } // BUG: hands out the internal list
int total() {
int t = 0;
for (int m : marks) t += m;
return t;
}
}
public class Main {
public static void main(String[] args) {
List<Integer> input = new ArrayList<>(List.of(70, 80, 90));
Marksheet sheet = new Marksheet("Asha", input);
System.out.println("Total: " + sheet.total());
input.add(100); // caller changes its own list...
sheet.getMarks().set(0, 0); // ...and someone edits through the getter
System.out.println("Total: " + sheet.total());
}
}
Total: 240
Total: 270
All fields were final, yet the total changed. final only stops the reference from pointing to a different list; it does not stop the list itself from being modified.
The fix: copy on the way in, and return something that cannot be modified. List.copyOf does both — it makes an unmodifiable copy:
import java.util.*;
final class Marksheet {
private final String student;
private final List<Integer> marks;
Marksheet(String student, List<Integer> marks) {
if (marks.isEmpty()) throw new IllegalArgumentException("no marks");
this.student = student;
this.marks = List.copyOf(marks); // defensive, unmodifiable copy
}
List<Integer> getMarks() { return marks; } // safe: callers cannot modify it
int total() {
int t = 0;
for (int m : marks) t += m;
return t;
}
}
public class Main {
public static void main(String[] args) {
List<Integer> input = new ArrayList<>(List.of(70, 80, 90));
Marksheet sheet = new Marksheet("Asha", input);
input.add(100);
try {
sheet.getMarks().set(0, 0);
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify marks");
}
System.out.println("Total: " + sheet.total());
}
}
Cannot modify marks
Total: 240
4. Value objects: equal when the contents are equal
A value object is a small immutable object defined entirely by its values: an amount of money, a date range, a roll number, a GPS point. Two Money objects of ₹500 are interchangeable — it does not matter which object you hold. Compare this with an entity like a Student, which has an identity (an ID) and stays the same student even when her phone number changes.
By default, Java's equals() compares references (are these the same object?), and so does hashCode(). For a value object that is wrong, and it breaks HashSet and HashMap:
import java.util.*;
final class RollNo {
private final String value;
RollNo(String value) { this.value = value; }
// equals and hashCode NOT overridden
}
final class RollNoFixed {
private final String value;
RollNoFixed(String value) { this.value = value; }
@Override
public boolean equals(Object o) {
return o instanceof RollNoFixed other && value.equals(other.value);
}
@Override
public int hashCode() { return value.hashCode(); }
}
public class Main {
public static void main(String[] args) {
Set<RollNo> a = new HashSet<>();
a.add(new RollNo("21CS001"));
System.out.println("Without equals: " + a.contains(new RollNo("21CS001")));
Set<RollNoFixed> b = new HashSet<>();
b.add(new RollNoFixed("21CS001"));
System.out.println("With equals: " + b.contains(new RollNoFixed("21CS001")));
}
}
Without equals: false
With equals: true
Rule to remember: if you override equals, you must override hashCode, so that equal objects have equal hash codes. Otherwise hash-based collections look in the wrong bucket.
5. Records: immutable value objects in one line
Since Java 16, a record writes all of this for you: private final fields, a constructor, accessor methods, equals, hashCode and toString. A compact constructor lets you add validation.
record Money(long paise) {
Money { // compact constructor: validation
if (paise < 0) throw new IllegalArgumentException("negative money");
}
Money plus(Money other) { return new Money(paise + other.paise); } // returns a NEW object
String show() { return "Rs " + paise / 100 + "." + String.format("%02d", paise % 100); }
}
public class Main {
public static void main(String[] args) {
Money fee = new Money(499900);
Money gst = new Money(89982);
Money total = fee.plus(gst);
System.out.println(total.show());
System.out.println(fee.show() + " (unchanged)");
System.out.println(new Money(100).equals(new Money(100)));
System.out.println(total);
try {
new Money(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Rs 5898.82
Rs 4999.00 (unchanged)
true
Money[paise=589882]
negative money
Two habits shown here are worth copying. First, money is stored as whole paise in a long, not as a double in rupees, because double cannot represent values like 0.1 exactly. Second, plus returns a new Money instead of changing fee — that is how every operation on an immutable object works.
A record's fields are final, but a record holding a List still needs List.copyOf in its compact constructor — the defensive-copy rule applies to records too.
Common mistakes
- Thinking
finalfields alone make a class immutable; afinalreference to a mutable list can still be changed through the list. - Returning the internal array or list from a getter.
- Overriding
equalswithouthashCode, which breaksHashSetandHashMap. - Using
doublefor money; uselongpaise orBigDecimal. - Calling
name.toUpperCase()and ignoring the result, expectingnameitself to change.
Quick recap
- Immutable = state fixed at construction; "changes" return new objects (
String,LocalDate,List.of). - Rules:
private finalfields, no setters,finalclass, validate in the constructor, defensive copies in and out. - Value objects (Money, RollNo) are compared by contents: override
equalsandhashCode. - Records generate the boilerplate; add validation in a compact constructor and still copy mutable inputs.