What are immutable objects and why are they important?
Why Interviewers Ask This
Senior OOP Concepts engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
An immutable object is one whose state cannot be changed after construction. Its fields are set during construction and never modified. Java's String, Integer, and all wrapper classes are immutable. Creating immutable class (Java): public final class ImmutablePerson { private final String firstName; private final String lastName; private final LocalDate birthDate; private final List<String> hobbies; // Defensive copy for mutable fields! public ImmutablePerson(String firstName, String lastName, LocalDate birthDate, List<String> hobbies) { this.firstName = firstName; this.lastName = lastName; this.birthDate = birthDate; this.hobbies = Collections.unmodifiableList(new ArrayList<>(hobbies)); // Defensive copy } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public LocalDate getBirthDate() { return birthDate; } public List<String> getHobbies() { return hobbies; // Already unmodifiable } // "Wither" methods -- return new instance with changed field: public ImmutablePerson withFirstName(String newFirstName) { return new ImmutablePerson(newFirstName, this.lastName, this.birthDate, this.hobbies); } }. Benefits of immutability: (1) Thread-safety: can safely share across threads without synchronization — immutable = inherently thread-safe; (2) No defensive copying needed for consumers: no risk that they modify your object; (3) Safe as Map keys/Set elements: hashCode won't change; (4) Simple reasoning: state never changes — easier to debug and test; (5) Caching: can safely cache and reuse; (6) Failure atomicity: if creation fails, no partial state exists. Java records (Java 14+): record Point(int x, int y) {} // Automatically immutable!. Kotlin data classes with val: data class Point(val x: Int, val y: Int). Value Objects in DDD are immutable. The more immutable your data, the fewer bugs from accidental mutation.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last OOP Concepts project, I used this when...' immediately makes your answer more credible and memorable.