How to Create an Immutable Class in Java
How to Create an Immutable Class in Java
In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once an object is created. In this section, we will learn how to create an immutable class in Java with the basic steps.
All the wrapper classes (like Integer, Boolean, Byte, etc.) and the String class is immutable. The immutable objects are never exposed to other objects to modify their state; only the constructor of immutable objects can initialize their fields.
Java allows us to create our custom immutable class using the final keyword.
The advantage of an immutable class is caching. Once the values are set, we don’t have to worry about the changes in values. Moreover, in the case of a multi-threaded environment, immutable class is inherently thread-safe.
Prerequisites to understand an immutable class:
- Java classes and objects
- Java Methods
Steps to Create an Immutable Class
To create a class immutable, we have to follow the steps given below:
- Declare a class as final using the final keyword so that no other class extends that class (i.e., no subclasses of that class can be created)
- Make all the data members private so that direct access won’t be allowed.
- Make all the data members in the class final so that they can be initialized only once inside the constructor, and once the object is created, their value cannot be changed.
- Do not define setter methods for the member variables so that there is no way to change the values of instance variables.
- Initialize all the fields with a parameterized constructor, which performs the deep copy. Thus the data members won’t be modified with the object reference.
- Perform deep copy of objects in the getter methods. The deep copy thus returns a copy of the objects instead of returning the actual object reference.
Example of an immutable Class
Let’s understand how to implement the above steps and create our immutable class with the following example:
ImmutableClassExample.java
//declaring the immutable class final class Student { private final int id; private final String name; //initializing data members using parameterized constructor public Student(int id, String name) { this.name = name; this.id = id; } //defining getter methods to return copy of data members public int getId() { return id; } public String getName() { return name; } } public class ImmutableClassExample{ public static void main(String[] args) { //creating the object of immutable class Student s = new Student(100, "Bob"); System.out.println("Id of the student:" +s.getId()); System.out.println("Name of the student: " +s.getName()); } }
Output:

Advantages of an Immutable Class
There are various advantages of immutable class in Java. They are as follows:
- It is inherently thread-safe and solves the traditionally used synchronization issues.
- It does not require a copy constructor.
- There is no need to implement the clone() method.
- It allows the hashCode() method to use lazy initialization and store its return value in the cache.
- It creates good Map keys and Set elements. (the state of these objects should not change in the collection).
- The class variant of an immutable class is created with its construction, and there is no need to check that again.
- It has failure atomicity (a term used by Joshua Bloch) which means if an immutable object throws an exception, it is not left in an indeterminate state.
Predefined Immutable Classes of Java
As mentioned earlier, Java contains some immutable classesare as follows:
- String
TheStringclassis the renowned immutable class of Java. The value of a string object cannot be changed once it is initialized. The String class methods like replace(), substring() returns a new instance and never affect the existing instance.
Example:
String str = "Hello World"; str = str.substring(1,7);
- Wrapper classes
The wrapper classes in Java like Integer, Float, Character, Boolean, Double, etc., are immutable. These classes do not change their state; they create a new instance whenever we modify them.
Example:
Integer var = 25; var *= 5;
The above example creates a new instance with a value of 125. However, once the var *=5 is called, and the current instance is lost.
Other than the String class and the wrapper classes, Java contains few more immutable classes, such as
- Immutable collection classes like Collections.singletonMap()
- Java enums
- StackTraceElement class of java.lang package
- Locale class of java.util.package
- UUID class of java.util package
In this way, we have learned how to create an immutable class in Java and some of the predefined immutable classes.