Home » Java Tutorial » Immutable Class in Java with Examples

Immutable Class in Java with Examples

An immutable class in java is a class whose values we can not change after the initialization. There are many immutable classes in java like int, float, char, string, etc. Immutable classes are beneficial for large scale applications. If we want to create an immutable class, we must declare it as a final to not create child classes.

What is the use of immutable class in java?

Nowadays, most applications must be distributive and multi-threaded. Multithreading causes developers a headache because they need to protect data from changing states. It isn’t easy to maintain the data state. For that case, we can use the immutable class. The immutable class in java never changes state. For every modification, we need to create a new instance. So that every thread has its unique value, and programmers need not worry about the modifications.

How to create immutable class in java?

To create immutable class in java, we need to follow the steps below.

  1. Declare a class as final so that other classes can not extend it.
  2. Make all the data members finals so that they will not be modified once initialized.
  3. Do not write setter methods in the class. The setter methods can change data members’ values.
  4. initializing all non-primitive mutable fields via constructor by performing a deep copy.
  5. While returning the value, avoid returning the whole object instead of that return the copy of it.

Advantages

Following are the advantages of immutable class in java

  1. Simple to write and understand
  2. It provides safety to threading.
  3. We can reuse the immutable class
  4. Sharing the internal data of the immutable class is possible.

Disadvantages

An immutable class’s main problem is that we need to declare separate instances for each distinct value. It is memory consuming while creating an instance every time, especially in a large application.

How to write immutable class in java?

public final class immutable_class {
    
    private final int roll_no; //declaration of variables
    private final String name;
    private final String cls;
    private final int marks;
     
    public immutable_class(int rno, String nm, String cls, int mrk)
    {
        this.roll_no = rno; //initialization
        this.name = nm;
        this.cls = cls;
        this.marks = mrk;
    }
    
    public static void main(String[] args) {
        //statements and operation
    }
    
}

Above is the way of creating an immutable class in java. We need to initialize the data members by a constructor or it will show errors.

Immutable class examples in java

In the example, we are declaring a custom immutable class in java. We declare four data members’ roll number, name, class, and marks of a student. We accept these values from the user and initialize the data member using a constructor. Also, we have declared one method which will calculate the percentage and return it to the main function. 

Example

import java.util.Scanner;

public final class student {
    
    private final int roll_no; //declaration of variables
    private final String name;
    private final String cls;
    private final int marks [] ;
     
    public student(int rno, String nm, String cls, int mrk [])
    {
        this.roll_no = rno; //initialization
        this.name = nm;
        this.cls = cls;
         this.marks = mrk;
    }
    
    public int getrno()
    {
        return roll_no;
    }
    
    public String getnm()
    {
        return name;
    }
    
    public String getcls()
    {
        return cls;
    }
    
   public float per()
    {
        int total = 0;
        for (int i = 0; i < marks.length; i++) {
            total = total + marks[i];
        }
        float per = (total/5);
        return per;
    }
    
    public static void main(String[] args) {
        int marks[] = new int [5]; 
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter roll number of student :");
        int rno = sc.nextInt();
        System.out.print("Enter name of student :");
        String nm = sc.next();
        System.out.print("Enter class of student :");
        String cls = sc.next();
        System.out.println("Enter marks of 5 subjects :");
        for (int i = 0; i < 5; i++) {
            System.out.print("Enter marks of subject "+i+1+" :");
           marks[i] = sc.nextInt();
        }
        student ob = new student(rno,nm,cls,marks);
        System.out.println("/n/nDetails of student :");
        System.out.println("Roll number : "+ob.getrno());
        System.out.println("Name : "+ob.getnm());
        System.out.println("Class : "+ob.getcls());
        System.out.println("Percentage : "+ob.per());
    }
    
}

Output

Enter roll number of student :101
Enter name of student :Pawan
Enter class of student :TY
Enter marks of 5 subjects :
Enter marks of subject 01 :100
Enter marks of subject 11 :90
Enter marks of subject 21 :80
Enter marks of subject 31 :70
Enter marks of subject 41 :90


Details of student :
Roll number : 101
Name : Pawan
Class : TY
Percentage : 86.0

How to create an immutable class in java without using final?

To create immutable class in java without using the final keyword, follow the steps below –

  1. Make all the data members private.
  2. Make the constructor private.
  3. Create one method which will return an instance of the class.

Example

public class demo {
    
    private int i;
     
   private demo(int n)
    {
        i = n;
    }
   
   private int display()
   {
       return i;
   }
   
    public static void main(String[] args) {
       demo ob = new demo(10);
        System.out.println(ob.display());
    }
    
}
Why string class is immutable in java?

If the String class is mutable, then the string will produce two hashcodes at the time of insertion and retrieval. For that matter, it will lose the data store in it. To avoid this problem, the java string class is immutable.

How to make a class immutable in java?

Declare a class and data members as final and initialize data members using a constructor. Please do not write any setter method in it.

Do you know?
1. Palindrome in Java
2. Wrapper class in Java
3. This Keyword in Java
4. Bubble Sort in Java
5. Armstrong Number in Java
6. Method overloading in java
7. Prime Number Program in Java
8. Type Casting In Java
9. Ternary Operator in Java
10. Immutable Class in Java

Pin It on Pinterest