×

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

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.