Quiz: Immutable Classes in Java: How to Create an Immutable Object
Study the lesson first: Immutable Classes in Java: How to Create an Immutable Object
Total: 8 questions
1. What is an immutable class in Java and how do you create one?
What is an immutable class in Java and how do you create one?
An immutable class is a class whose objects cannot change state after they are created. All values are set in the constructor, and methods that look like modifications return a new object. String, Integer, LocalDate and BigDecimal work this way.
A class is immutable only when all five rules hold:
- 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 (
List, array,Date) are copied; - methods never return references to mutable internal objects, only a copy or an unmodifiable view.
Rules 4 and 5 are the ones people forget: final stops a field from being reassigned, but not the list it points to from being changed. If every field is a primitive or an already immutable type, rules 4 and 5 hold by themselves. Validation and Objects.requireNonNull() belong in the constructor: an immutable object has no other place where it could become valid.
2. Why use immutable objects, what do they cost, and does immutability protect against reflection?
Why use immutable objects, what do they cost, and does immutability protect against reflection?
Benefits:
- thread safety without synchronization: the object can be shared with any number of threads;
- safe
HashMapkeys andHashSetelements:hashCode()never changes, so an entry is never "lost"; - the object can be passed to any method without defensive copies;
- caching and reuse of one instance, like the string pool and the
Integer.valueOf()cache for -128 to 127; - an invariant is checked once in the constructor and stays true for the whole life of the object.
Cost: every "change" creates a new object. For money, dates and coordinates this is almost free; for objects that change often and as a whole (a buffer filled in a loop, a large matrix) you use a mutable companion such as StringBuilder. JPA and Hibernate entities are usually mutable too.
Reflection: in a regular class, after setAccessible(true), calling field.setInt(obj, 42) overwrites a private final field; for a record the same call throws IllegalAccessException. In JDK 26 (JEP 500) such a write prints a warning by default. Immutability protects against bugs in code, not against someone who breaks encapsulation on purpose.
3. What is a defensive copy in a constructor, why copy before validating, and why is a Date not copied with clone()?
What is a defensive copy in a constructor, why copy before validating, and why is a Date not copied with clone()?
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: the instance no longer depends on it.
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);
}
}
Copy first, then validate: if you check the originals and copy afterwards, another thread holding the same Date can change it in between, and the object stores values that never passed the check. Nobody but the constructor can see the copies.
Not clone(): Date is not final, so the caller can pass a subclass with an overridden clone(). new Date(from.getTime()) always creates a real Date. Better still, use LocalDate or Instant: they are immutable and need no copy.
How to copy: List.copyOf(), Set.copyOf(), Map.copyOf() for collections, array.clone() or Arrays.copyOf() for an array, a copy constructor for your own mutable class. String, Integer, LocalDate and a record of immutable fields need no copy.
4. Why do getters need defensive copies, and how do you return an array or a list?
Why do getters need defensive copies, and how do you return an array or a list?
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 state. For example, exam.getScoresLeaky()[0] = 0 changes the scores inside the object even though the constructor called scores.clone().
An array is always mutable and has no unmodifiable view, so every call to the getter returns a fresh copy: return scores.clone();.
A collection has two options:
// 1: unmodifiable copy in the field, the getter copies nothing
this.skills = List.copyOf(skills);
public List<String> getSkills() { return skills; }
// 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 1 is cheaper and usually preferred. Option 2 is for classes that change the list internally, which is rare in an immutable class.
5. What is the difference between List.copyOf(), Collections.unmodifiableList() and stream().toList()?
What is the difference between List.copyOf(), Collections.unmodifiableList() and stream().toList()?
The key difference is whether you get a copy or a view on top of the original list:
Collections.unmodifiableList(src)(Java 1.2) is a view: you cannot change the list through it, but every change tosrcshows through. On its own it is not a defensive copy; it acceptsnull.List.copyOf(src)(Java 10) is an unmodifiable copy that does not see changes tosrc; it throwsNullPointerExceptionon anullelement.src.stream().toList()(Java 16) is an unmodifiable copy that acceptsnull.Collections.unmodifiableList(new ArrayList<>(src))is a copy in a wrapper that acceptsnull.
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]
The List.copyOf() optimization: if the list is already unmodifiable (the result of List.of() or another copyOf()), the same object is returned without copying, so List.copyOf(skills) == skills is true. That is why withSalary() can pass skills to the new constructor for free. unmodifiableList() cannot do this.
6. What is the difference between deep and shallow immutability, and which JDK classes are immutable?
What is the difference between deep and shallow immutability, and which JDK classes are immutable?
Shallow immutability: you cannot replace a field or add or remove a list element, but you can change the element itself. List.copyOf() copies the list, not its elements: if a Course holds a mutable Lesson, calling lesson.setTitle("Changed") changes the course too. In the same way, List.of(new StringBuilder("a")) will not let you add an element, but get(0).append("b") works.
Deep immutability: every object reachable from the fields is immutable. Only deep immutability gives real guarantees, such as thread safety and a stable hashCode(). Two ways to get it: make the elements immutable (for example record Lesson(String title)), which is the best option, or deep-copy every element on the way in and out, which is expensive and easy to miss in one spot.
Immutable JDK classes: String, the wrappers (Integer, Long, Double...), BigInteger, BigDecimal, LocalDate, LocalDateTime, Instant, Duration, ZonedDateTime, collections from List.of()/Set.of()/Map.of()/List.copyOf(), Optional, UUID, Path, Pattern. Mutable counterparts: StringBuilder, AtomicInteger, Date, Calendar, ArrayList, arrays. An enum is immutable only as long as you add no mutable fields to it.
7. How do you "change" an immutable object, and what is the most common mistake with such methods?
How do you "change" an immutable object, and what is the most common mistake with such methods?
Instead of a setter you write a method that returns a new instance with one field set to a different value. It is called withXxx(), like LocalDate.withYear(), or named after the operation: plusDays(), BigDecimal.add(), String.toUpperCase().
public Employee withSalary(int newSalary) {
return new Employee(name, newSalary, skills);
}
anna.withSalary(2000); // the result is lost
Employee promoted = anna.withSalary(2000); // correct
System.out.println(anna.getSalary()); // 1000: the original did not change
The most common mistake is calling such a method and not keeping the result: s.toUpperCase();, date.plusDays(1);, bd.add(BigDecimal.ONE);. The compiler does not catch it, which makes it a favourite trap in interviews and on the OCP exam.
With many fields, instead of ten with methods you add a mutable Builder next to the class: you fill it with setters, and build() calls the immutable class constructor once, just like the StringBuilder → String pair.
8. Why must an immutable class be final, and which rules does a record satisfy for you?
Why must an immutable class be final, and which rules does a record satisfy for you?
Even with private final fields, a class that is not final can be extended: a MutablePoint subclass overrides getX(), adds setX(), and code that works with Point sees a changing value. There are two ways to forbid inheritance:
- declare the class
final: a subclass fails withcannot inherit from final Point; - make every constructor
privateand create objects through a factory,Point.of(1): a subclass cannot callsuper(...), and the factory can cache common values the wayInteger.valueOf()does.
A historical example of breaking this rule: BigInteger and BigDecimal are not final. A method that receives them from untrusted code has to check the exact class or make a copy: new BigInteger(arg.toByteArray()). String, the wrappers and java.time are final.
A record (Java 16) satisfies three of the five rules: it is implicitly final, its fields are private final, and it has no setters. Defensive copies are still your job: skills = List.copyOf(skills); in the compact constructor. You need a regular class instead of a record to hide some fields, keep a cache (like the hashCode of String) or extend another class. Lombok @Value also makes the class final with private final fields, but, like a record, it makes no copies.