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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
