Java Immutability - Interview Questions & Answers

Master Java Immutability with interview-focused questions and answers. Learn immutable objects, immutable classes, String immutability, defensive copying, thread safety, and enterprise best practices with Java examples.


Java Immutability - Interview Questions & Answers

Introduction

Immutability is one of the most important concepts in Java and is frequently asked in interviews ranging from Junior Java Developer to Solution Architect.

An immutable object cannot be modified after it is created.

Many core Java classes are immutable because immutable objects are:

  • Thread-safe
  • Easy to cache
  • Easy to debug
  • Secure
  • Reliable

Examples include:

  • String
  • Integer
  • Long
  • BigDecimal
  • LocalDate
  • UUID

Why Interviewers Ask About Immutability?

Interviewers want to evaluate your understanding of:

  • Object-Oriented Design
  • Thread Safety
  • Java Memory Model
  • Collections
  • Performance
  • Effective Java Best Practices
flowchart LR

ObjectCreation --> ImmutableObject

ImmutableObject --> ThreadSafe

ImmutableObject --> CacheFriendly

ImmutableObject --> ReliableApplication

Interview Question 1

What is Immutability?

Answer

An object is immutable if its state cannot be changed after creation.

Once an immutable object is created:

  • No field can be modified.
  • No setter methods exist.
  • A new object must be created for any change.

Java Example

String first = "Java";

String second = first.concat(" 21");

System.out.println(first);

System.out.println(second);

Output

Java

Java 21

The original String object remains unchanged.


Diagram

flowchart LR

StringJava["String: Java"] --> concat

concat --> NewObject["String: Java 21"]

StringJava --> OriginalUnchanged

Interview Tip

A good interview answer:

Immutable objects never change their internal state after construction.


Interview Question 2

Why are Immutable Objects Important?

Answer

Immutable objects provide several advantages.

Benefits

  • Thread-safe
  • Safe sharing
  • Easy caching
  • Predictable behavior
  • Easier debugging
  • Better security
  • No synchronization required

Diagram

mindmap
  root((Immutable))
    Thread Safe
    Secure
    Reliable
    Cache Friendly
    Easy Debugging
    Performance

Real-World Example

A banking application stores customer account numbers as immutable objects.

Since account numbers never change, multiple threads can safely access them without synchronization.


Interview Tip

Mention that immutable objects reduce concurrency-related bugs.


Interview Question 3

Why is String Immutable?

Answer

String is immutable for several important reasons.

Security

Strings store:

  • Passwords
  • URLs
  • Database Connections
  • File Paths

Changing them unexpectedly could create security risks.


String Pool

String immutability enables String Pool optimization.

String a = "Java";

String b = "Java";

Both variables reference the same object.


Hashing

Strings are commonly used as keys in:

  • HashMap
  • HashSet

Stable hash codes improve lookup performance.


Diagram

flowchart LR

StringPool --> JavaObject

VariableA --> JavaObject

VariableB --> JavaObject

Interview Tip

This is one of the most common Java interview questions.

Remember the four key reasons:

  • Security
  • String Pool
  • Thread Safety
  • HashMap Performance

Interview Question 4

How do you create an Immutable Class?

Answer

Follow these rules:

  • Declare the class final.
  • Make all fields private final.
  • Initialize fields in the constructor.
  • Do not provide setter methods.
  • Return defensive copies for mutable fields.

Java Example

public final class Employee {

    private final int id;

    private final String name;

    public Employee(int id, String name) {

        this.id = id;

        this.name = name;

    }

    public int getId() {

        return id;

    }

    public String getName() {

        return name;

    }

}

Diagram

flowchart LR

Constructor --> FinalFields

FinalFields --> NoSetters

NoSetters --> ImmutableObject

Interview Tip

If a class has setter methods, it is generally not immutable.


Interview Question 5

How does Immutability improve Thread Safety?

Answer

Multiple threads can safely read immutable objects because their state never changes.

No synchronization is required.


Mutable Object

sequenceDiagram
participant Thread1
participant Employee
participant Thread2
Thread1->>Employee: Update Salary
Thread2->>Employee: Read Salary
Note over Employee: Race Condition Possible

Immutable Object

sequenceDiagram
participant Thread1
participant Employee
participant Thread2
Thread1->>Employee: Read
Thread2->>Employee: Read
Note over Employee: Safe Concurrent Access

Java Example

LocalDate joiningDate = LocalDate.now();

LocalDate nextYear = joiningDate.plusYears(1);

System.out.println(joiningDate);

System.out.println(nextYear);

The original object is unchanged.


Interview Tip

Immutable objects eliminate most synchronization problems because they cannot be modified after creation.



Interview Question 6

What is Defensive Copying?

Answer

Defensive Copying means returning a copy of mutable objects instead of exposing internal references.

Without defensive copying, external code can modify an object's internal state.


Bad Example

public class Employee {

    private Date joiningDate;

    public Date getJoiningDate() {

        return joiningDate;

    }

}

Anyone can modify joiningDate.


Good Example

public class Employee {

    private final Date joiningDate;

    public Employee(Date joiningDate) {

        this.joiningDate = new Date(joiningDate.getTime());

    }

    public Date getJoiningDate() {

        return new Date(joiningDate.getTime());

    }

}

Diagram

flowchart LR

InternalObject --> DefensiveCopy

DefensiveCopy --> Client

Client -. Cannot Modify .-> InternalObject

Interview Tip

Defensive copying is required only for mutable objects like Date, List, or arrays.


Interview Question 7

What is the difference between Mutable and Immutable Objects?

Answer

Mutable Immutable
Can change after creation Cannot change after creation
Not thread-safe by default Thread-safe
Requires synchronization No synchronization required
Examples: ArrayList, Date Examples: String, Integer, LocalDate

Diagram

flowchart LR

Object --> Mutable

Object --> Immutable

Mutable --> ChangeState

Immutable --> FixedState

Java Example

Mutable

List<String> names = new ArrayList<>();

names.add("Java");

Immutable

String language = "Java";

language.concat(" 21");

The original string remains unchanged.


Interview Tip

Remember:

Every immutable object is read-only after construction.


Interview Question 8

What are Immutable Collections in Java?

Answer

Java provides immutable collections that cannot be modified after creation.

Examples:

List<String> languages =
        List.of("Java", "Spring", "Kafka");

Attempting to modify it throws an exception.


Java Example

languages.add("Docker");

Output

UnsupportedOperationException

Diagram

flowchart LR

List.of() --> ImmutableList

ImmutableList --> ReadOnly

ReadOnly --> SafeSharing

Interview Tip

Collections.unmodifiableList() creates an unmodifiable view, while List.of() creates a truly immutable collection.


Interview Question 9

What are the common mistakes when creating Immutable Classes?

Answer

Avoid these mistakes:

❌ Providing setter methods

❌ Forgetting the final keyword

❌ Returning mutable fields directly

❌ Accepting mutable objects without defensive copying

❌ Allowing subclassing


Diagram

flowchart TD

BadDesign --> Setters

BadDesign --> MutableFields

BadDesign --> MissingFinal

BadDesign --> NoDefensiveCopy

Interview Tip

Always review every field in an immutable class to ensure it cannot be modified indirectly.


Interview Question 10

What are the Best Practices for Designing Immutable Classes?

Answer

Follow these best practices:

  • Make the class final.
  • Declare fields as private final.
  • Initialize fields in the constructor.
  • Avoid setter methods.
  • Perform defensive copying for mutable fields.
  • Return immutable collections when possible.
  • Validate constructor arguments.

Diagram

flowchart LR

ImmutableClass --> FinalClass

ImmutableClass --> FinalFields

ImmutableClass --> NoSetters

ImmutableClass --> DefensiveCopy

ImmutableClass --> ThreadSafe

Interview Tip

Immutable classes are ideal for:

  • Configuration objects
  • Value Objects
  • DTOs
  • Money
  • Dates
  • Cache keys
  • Identifiers

Common Interview Mistakes

  • Confusing final with immutability.
  • Assuming all final objects are immutable.
  • Returning mutable collections directly.
  • Forgetting defensive copying.
  • Believing immutable objects consume more memory.
  • Ignoring immutable collections introduced in Java 9.

Quick Revision

Concept Key Point
Immutability Object state never changes
Immutable Class No setters, final fields
String Immutable for security and performance
Defensive Copy Protect mutable fields
Thread Safety Immutable objects are naturally thread-safe
Mutable Object State can change
Immutable Collection Read-only collection
Final Prevents reassignment, not object mutation
Best Practice Prefer immutable objects whenever possible
Enterprise Usage Configuration, DTOs, Cache Keys, Value Objects

Interviewer's Expectations

Junior Java Developer

  • Explain immutable objects.
  • Create a simple immutable class.
  • Understand why String is immutable.

Senior Java Developer

  • Explain defensive copying.
  • Compare mutable and immutable objects.
  • Discuss thread safety.
  • Design immutable domain models.

Solution Architect

  • Promote immutability in concurrent systems.
  • Choose immutable data structures where appropriate.
  • Balance performance, memory usage, and maintainability.
  • Explain trade-offs between mutable and immutable designs.

Related Interview Questions

  • Why is String immutable?
  • What is Defensive Copying?
  • Difference between final and immutability?
  • What is Thread Safety?
  • What are Value Objects?
  • What is the Builder Pattern?
  • What are Immutable Collections?
  • Explain Collections.unmodifiableList() vs List.of().
  • How does immutability improve concurrent programming?
  • What are Java Records?

Summary

Immutability is a core principle of Java and modern software design. Immutable objects simplify concurrent programming, improve reliability, and make applications easier to maintain. Java itself embraces immutability through classes like String, Integer, and LocalDate, and Effective Java strongly recommends using immutable objects whenever practical.

For interviews, don't just define immutability. Explain how to build immutable classes, why String is immutable, how defensive copying protects mutable fields, and how immutability improves thread safety and application design. Real-world examples and trade-off discussions will help demonstrate senior-level Java expertise.