Java / Java 21 Interview Questions
Why is immutability important in Java and how do you implement it correctly?
An immutable object's state cannot change after construction. Immutable objects are inherently thread-safe, can be freely shared without copying, make better HashMap keys, and simplify reasoning about code because no method can have hidden side effects on them.
// Building an immutable class correctly
public final class Money { // 1. final class — no subclassing
private final BigDecimal amount; // 2. private final fields
private final Currency currency;
private final List notes; // 3. defensive copy of mutable input
public Money(BigDecimal amount, Currency currency, List notes) {
this.amount = Objects.requireNonNull(amount);
this.currency = Objects.requireNonNull(currency);
// Defensive COPY — don't store caller's mutable list
this.notes = List.copyOf(notes); // unmodifiable copy
}
public BigDecimal getAmount() { return amount; }
public Currency getCurrency() { return currency; }
public List getNotes() { return notes; } // safe — unmodifiable
// Return new instance for 'mutations'
public Money add(Money other) {
if (!this.currency.equals(other.currency))
throw new IllegalArgumentException("Currency mismatch");
return new Money(this.amount.add(other.amount), this.currency, notes);
}
}
// Records are immutable by default (final, final fields, no setters)
record Point(int x, int y) {}
// Java 9+ — unmodifiable collection factories
List immList = List.of("a", "b", "c"); // unmodifiable
Map immMap = Map.of("k", 1); // unmodifiable
// Collections.unmodifiable* wraps but the underlying can still be mutated
var inner = new ArrayList<>(List.of("a"));
var wrapped = Collections.unmodifiableList(inner);
inner.add("b"); // wrapped now also reflects the change! The subtle pitfall: Collections.unmodifiableList(list) creates a view — not a copy. If the backing list is mutated through the original reference, the view reflects the change. List.copyOf() (Java 10) creates a true immutable snapshot.
More Related questions...