How to create Immutable class in Java?

Immutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well.

Following are the requirements:

  • The class must be declared as final (So that child classes can’t be created)
  • Data members in the class must be declared as final (So that we can’t change the value of it after object creation)
  • A parameterized constructor
  • Getter method for all the variables in it
  • No setters(To not have the option to change the value of the instance variable)

Example to create Immutable class





// An immutable class
public final class Student
    final String name;
    final int regNo;
    public Student(String name, int regNo)
    { = name;
        this.regNo = regNo;
    public String getName()
        return name;
    public int getRegNo()
        return regNo;
// Driver class
class Test
    public static void main(String args[])
        Student s = new Student("ABC", 101);
        // Uncommenting below line causes error
        // s.regNo = 102;




In this example, we have created a final class named Student. It has two final data members, a parameterized constructor and getter methods. Please note that there is no setter method here.
(In order to make it functional, create objects of Student class in the main function.)

This article is contributed by Abhishree Shetty. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Improved By : SunnyGunnam, ADILKHAN6

Article Tags :
Practice Tags :


Please write to us at to report any issue with the above content.