Java Basics — All about Immutable class with examples

Java Basics — All about Immutable class with examples

Immutable — The term in Java as a beginner is hard to interpret and understand but I will try to make it easy for you.

What does immutable means?

In dictionary, meaning of immutable is something that does not change over a period of time. Here in java it also reflects the same. An immutable class object is not changed once it is created.

Why do we require an immutable class?

  • As immutable class objects cannot be changed, it is thread-safe. You can access the values of objects from any thread and it would be the same.
  • The internal state of the object is always consistent
  • If we are using caching techniques, we can prefer immutable objects as they wouldn’t change.

Examples of immutable classes are all wrapper classes like String, Integer, etc.,

How to create an immutable class?

  • Make the class final, so that it cannot be extended.
  • No setter methods are to be provided in the class, so that the values cannot be modified externally.
  • All the fields should be marked as private and final as it is not exposed to the outside world and can be updated only via the constructor
  • Parameterized constructor made public which updates the values during the object creation.
  • Getter methods should return a copy of the reference and not the original object so that it cannot be manipulated.

Let us see an example

Immutable Class

Let us create an object of the class and then try changing the value

The main method calling the immutable class

the output of the above program is

Output of the above program

In the above program, we see that the values are set to the object once during the object creation, and trying to change the values is not possible.

The getter methods of String and Integer directly return the value as they are wrapper classes and are immutable by default. But while returning the metadata we created a copy of the values and returns the new reference object and the original object remains untouched.