×

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:

  1. 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)
  2. Make all the data members private so that direct access won’t be allowed.
  3. 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.
  4. Do not define setter methods for the member variables so that there is no way to change the values of instance variables.
  5. 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.
  6. 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:

How to Create an Immutable Class in Java

Advantages of an Immutable Class

There are various advantages of immutable class in Java. They are as follows:

  1. It is inherently thread-safe and solves the traditionally used synchronization issues.
  2. It does not require a copy constructor.
  3. There is no need to implement the clone() method.
  4. It allows the hashCode() method to use lazy initialization and store its return value in the cache.
  5. It creates good Map keys and Set elements. (the state of these objects should not change in the collection).
  6. The class variant of an immutable class is created with its construction, and there is no need to check that again.
  7. 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:

  1. 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.


Related Topics

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.