00:00

How to Create an Immutable Class in Java

Last updated:

In this tutorial, we will explore the concept of immutable objects in Java and learn how to design and implement a custom immutable class with practical examples.

In Java, an immutable object is an object whose state cannot be changed after it is created. Once initialized, its existing values remain unchanged throughout its lifetime. If different values are required, a new object must be created instead of modifying the existing one.

Immutable objects help maintain data consistency, prevent unintended modifications, and simplify programming in multithreaded environments.

Note: Java provides many built-in immutable classes, such as String, the wrapper classes (Integer, Long, Float, etc.), BigInteger, BigDecimal, Locale and the java.time classes such as LocalDate.

1. Rules for Creating an Immutable Class

To create an immutable class in Java, follow these rules:

  1. Declare the class as final so no other class can extend it.
  2. Declare all data members private so they cannot be accessed directly from outside the class.
  3. Declare all data members final so their values cannot change after the object is created.
  4. Initialize all fields in a constructor, and performing a deep copy so that data members can't be modified with an object reference.
  5. Provide only getter methods. For mutable fields, the getter should return a copy instead of the actual object reference.
  6. Do not provide setter methods, or any other method that changes the object's state.
  7. Do not allow another thread or object to access your object before its constructor has finished executing. This is called constructor reference escape or this escape in Java.

2. Example: A Custom Immutable Class

Let's understand a custom immutable class with the help of the example below. All fields of Student are String or int, which are already immutable, so no copies are needed.

ImmutableExample.java
// Declare class as final so it cannot be extended
final class Student {
    // Declare data members as private and final
    private final String studentName;
    private final String className;
    private final int rollNo;

    // Parameterized constructor initializes all fields once
    public Student(String studentName, String className, int rollNo) {
        this.studentName = studentName;
        this.className = className;
        this.rollNo = rollNo;
    }

    // Getter methods to access data outside the class
    // No setter methods are provided
    public String getStudentName() {
        return studentName;
    }

    public String getClassName() {
        return className;
    }

    public int getRollNo() {
        return rollNo;
    }
}

public class ImmutableExample {
    public static void main(String[] args) {
        // Create an object of the immutable class Student
        Student stuObject = new Student("Shreyansh Shanu", "Nursery", 11);
        System.out.println("Student Name: " + stuObject.getStudentName());
        System.out.println("Student Class: " + stuObject.getClassName());
        System.out.println("Student Roll No.: " + stuObject.getRollNo());
    }
}
Output
Student Name: Shreyansh Shanu
Student Class: Nursery
Student Roll No.: 11

3. Immutable Class with Mutable Fields

If a field refers to a mutable object such as a List, Date or array, marking it final is not enough: final only stops the reference from changing, not the object it points to. Make a copy in the constructor and in the getter, so no outside code ever holds a reference to the internal object.

DefensiveCopyExample.java
import java.util.ArrayList;
import java.util.List;

final class Employee {
    private final String name;
    private final List<String> skills; // List is mutable

    public Employee(String name, List<String> skills) {
        this.name = name;
        // Defensive copy: later changes to the caller's list do not affect this object
        this.skills = new ArrayList<>(skills);
    }

    public String getName() {
        return name;
    }

    public List<String> getSkills() {
        // Return a copy so callers cannot modify the internal list
        return new ArrayList<>(skills);
    }
}

public class DefensiveCopyExample {
    public static void main(String[] args) {
        List<String> skills = new ArrayList<>();
        skills.add("Java");
        skills.add("SQL");

        Employee emp = new Employee("Asha", skills);

        // Try to change the employee's skills from outside
        skills.add("Python");
        emp.getSkills().add("Go");

        System.out.println("Caller's list: " + skills);
        System.out.println("Employee skills: " + emp.getSkills());
    }
}
Output
Caller's list: [Java, SQL, Python]
Employee skills: [Java, SQL]

Changes made to the caller's list and to the list returned by getSkills() do not affect the Employee object.

Tip: Since Java 10, List.copyOf(skills) creates an unmodifiable copy in one step, so the getter can return the field directly. Note that it rejects null elements, and a copy protects only the list itself: if the elements are mutable objects, they must be copied or made immutable too.

4. Immutable Classes with Records (Java 16+)

A record is a compact way to declare an immutable data class. A record is implicitly final, each component is stored in a private final field, and it has no setters. The compiler also generates the canonical constructor, the accessor methods, equals(), hashCode() and toString(). Records are only shallowly immutable, so mutable components still need a defensive copy, which you can make in a compact constructor.

RecordExample.java
import java.util.List;

// A record is final, its fields are private and final, and it has no setters
record Product(String name, double price, List<String> tags) {
    // Compact constructor: make an unmodifiable copy of the mutable list
    Product {
        tags = List.copyOf(tags);
    }
}

public class RecordExample {
    public static void main(String[] args) {
        Product p = new Product("Laptop", 899.99, List.of("electronics", "computers"));
        System.out.println(p);
        System.out.println("Name: " + p.name() + ", Price: " + p.price());

        try {
            p.tags().add("sale");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify tags: " + e.getClass().getSimpleName());
        }
    }
}
Output
Product[name=Laptop, price=899.99, tags=[electronics, computers]]
Name: Laptop, Price: 899.99
Cannot modify tags: UnsupportedOperationException

5. Immutable Value Types in Java 21 and Java 25

Recent Java releases make immutable value types easier to write and use. The example below models an amount of money as a record and uses two newer features:

  • Record patterns (Java 21): instanceof Money(long paise, String currency) checks the type and extracts the components in one step.
  • Flexible constructor bodies (Java 25): a constructor can run statements, such as parsing or validating its input, before calling this(...) or super(...). Those statements cannot use the object under construction.
MoneyExample.java
import java.math.BigDecimal;
import java.util.Objects;

// An immutable value type written as a record
record Money(long paise, String currency) {

    // Compact constructor: validate once, so every Money object is valid
    Money {
        Objects.requireNonNull(currency, "currency");
        if (paise < 0) {
            throw new IllegalArgumentException("Amount cannot be negative: " + paise);
        }
    }

    // Java 25: statements may run before this(...) in a constructor
    Money(String text) {                          // for example "INR 1250.50"
        String[] parts = text.trim().split(" ");
        long paise = new BigDecimal(parts[1]).movePointRight(2).longValueExact();
        this(paise, parts[0]);
    }

    // "Changing" an immutable object means returning a new one
    Money plus(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("Currency mismatch: " + other.currency);
        }
        return new Money(paise + other.paise, currency);
    }
}

public class MoneyExample {
    public static void main(String[] args) {
        Money price = new Money("INR 1250.50");
        Money total = price.plus(new Money(4950, "INR"));

        System.out.println("Price : " + price);
        System.out.println("Total : " + total);

        // Record pattern (Java 21+): read the components in one step
        if (total instanceof Money(long paise, String currency)) {
            System.out.printf("Pay   : %s %d.%02d%n", currency, paise / 100, paise % 100);
        }

        try {
            new Money(-1, "INR");
        } catch (IllegalArgumentException e) {
            System.out.println("Error : " + e.getMessage());
        }
    }
}
Output
Price : Money[paise=125050, currency=INR]
Total : Money[paise=130000, currency=INR]
Pay   : INR 1300.00
Error : Amount cannot be negative: -1

How the code works

  1. The compact constructor validates every new Money object, so an invalid amount can never exist.
  2. The Money(String) constructor parses the text before calling this(...). Before Java 25, this code did not compile, and the parsing had to be moved into a static helper method.
  3. plus() does not change price; it returns a new Money object, which is how all immutable classes handle "changes".
  4. The amount is stored in paise as a long and parsed with BigDecimal, which avoids floating-point rounding errors.

Compile and run this example with JDK 25 or later. With an earlier JDK, the Money(String) constructor causes a compilation error.

6. Benefits of Immutable Classes

Immutable classes offer several advantages by ensuring that an object's state remains unchanged after creation. The key benefits include:

  1. Thread Safety: Immutable objects can be safely shared across multiple threads without synchronization, provided they are properly constructed and safely used.
  2. Data Consistency: Since the object's state cannot change after creation, its values remain consistent throughout its lifetime.
  3. Improved Security: Immutability prevents unintended modifications to an object's internal state, reducing the risk of accidental data changes.
  4. Simplified Maintenance: Immutable objects are easier to understand, debug, and maintain because their state does not change unexpectedly.
  5. Safe Use as Map Keys: Immutable objects are suitable for use as keys in HashMap because their state remains stable. However, their equals() and hashCode() implementations must follow the required contracts.
  6. Safe Object Sharing: Immutable objects can be shared and reused across different parts of an application without the risk of one component modifying their state.
  7. Reliable Caching: Immutable objects are well-suited for caching because their state remains unchanged, reducing the need for defensive copying and synchronization.

7. Summary

  • An immutable object's state cannot change after it is created.
  • Make the class final, the fields private final, and provide no setters.
  • Copy mutable objects in the constructor and in getters; List.copyOf() (Java 10+) helps with lists.
  • Do not let the object's reference escape from the constructor.
  • From Java 16, records are the shortest way to write an immutable data class.
  • Java 21 record patterns and Java 25 flexible constructor bodies make immutable value types easier to use and to build.

8. References