×

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

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Difference between = = and equals ( ) in java

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

6 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.