100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What is Immutability in OOP?

Immutability in OOP explained — thread safety, defensive copying and Java String examples, with interview Q&A.

mediumQ56 of 226 in Object Oriented Programming Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

Immutability means an object’s observable state cannot change after it is constructed — every field is fixed for the lifetime of the object, so any operation that appears to modify it actually returns a new object instead.

An immutable class typically declares all fields `final` and `private`, assigns them only in the constructor, exposes no setters, and — critically — either avoids mutable field types or defensively copies them so a caller cannot reach in and change internal state through a returned reference. Java’s `String` is the canonical example: every `concat`, `replace`, or `substring` call returns a brand-new `String` rather than altering the original. Immutable objects are inherently thread-safe with no synchronization needed (since there is no state to race on), safe to share and cache freely, safe as hash-map keys (their hash code never changes), and easier to reason about since their state can never drift unexpectedly. The tradeoff is potential extra allocation when a value changes frequently, which is why mutable builders (like `StringBuilder`) exist alongside immutable value types for performance-sensitive accumulation.

  • Automatically thread-safe with no locking required
  • Safe to share, cache, and reuse without defensive copying by callers
  • Reliable as hash-map/hash-set keys since hashCode never changes
  • Eliminates a whole class of bugs from unexpected state mutation

AI Mentor Explanation

Once a match’s official scorecard is printed and archived after the final ball, it can never be edited — any correction produces an entirely new archived record rather than altering the original. Anyone holding a copy of that scorecard can trust it will read exactly the same forever, with no need to double-check it later. That is immutability: once the object is finalized, its state is locked, and any "change" actually produces a new object rather than mutating the original.

Step-by-Step Explanation

  1. Step 1

    Make fields final and private

    Declare all instance fields as `private final` so they can only be set once, in the constructor.

  2. Step 2

    Assign only in the constructor

    Fully initialize the object in a single constructor call; provide no setters.

  3. Step 3

    Defensively copy mutable inputs

    If a field references a mutable type (e.g. a Date or List), copy it in and copy it out to prevent external mutation.

  4. Step 4

    Return new objects on "change"

    Any operation that looks like it mutates state instead constructs and returns a new immutable instance.

What Interviewer Expects

  • Correct definition and understanding that "change" means creating a new object
  • Awareness that immutability provides free thread-safety
  • Knowledge of defensive copying for mutable field types
  • A concrete example like String or a custom immutable value class

Common Mistakes

  • Believing `final` alone makes an object immutable, without checking mutable field types
  • Forgetting defensive copies for mutable fields like arrays, dates, or collections
  • Assuming immutable objects can never be garbage-collected differently or reused
  • Confusing immutability with `const`/`readonly` at the variable level rather than the object level

Best Answer (HR Friendly)

An immutable object is one whose data can never change after it’s created — if you need a different value, you get back a brand-new object instead of the original one being altered. This is why Strings in Java are immutable: every method that looks like it modifies a string actually returns a new one. It’s valuable because immutable objects are automatically safe to share across threads and can’t be accidentally corrupted by code that holds a reference to them.

Code Example

An immutable Point class
public final class Point {
    private final double x;
    private final double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() { return x; }
    public double getY() { return y; }

    // "Mutation" returns a brand-new Point, original stays untouched
    public Point translate(double dx, double dy) {
        return new Point(this.x + dx, this.y + dy);
    }
}

Point p1 = new Point(1, 2);
Point p2 = p1.translate(3, 4); // p1 is unchanged; p2 is a new object
System.out.println(p1.getX()); // still 1

Follow-up Questions

  • Why is String immutable in Java, and what are the benefits of that design choice?
  • How would you make a class with a mutable field (e.g. a List) truly immutable?
  • Why are immutable objects automatically thread-safe?
  • What is the performance tradeoff of immutability, and how does StringBuilder address it?

MCQ Practice

1. What does it mean for an object to be immutable?

Immutability means the object's state is fixed after construction; apparent mutations return new instances.

2. Why are immutable objects inherently thread-safe?

With no state that can change, concurrent reads from multiple threads cannot produce a data race.

3. What extra step is needed to make a class with a mutable field (like a Date) truly immutable?

`final` only prevents reassigning the reference; defensive copies stop external code from mutating the referenced object.

Flash Cards

Immutability in one line?An object's state cannot change after construction — updates return new objects.

Canonical immutable example?Java's String — every "modifying" method returns a new String.

Key benefit?Automatic thread-safety, since there is no mutable state to synchronize.

Common pitfall?Forgetting to defensively copy mutable field types like dates or lists.

1 / 4

Continue Learning