×

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

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.