Immutable class in Java

Posted By : Lokesh Kumar | 28-Dec-2017
Immutable class means any changes made to this class's object will create a new object. In Java String and all the Wrapper (Integer, Boolean etc) classes are the immutable.
 
For eg:
  String str = "ABC";
  str + = " XYZ";
 
Now in the above example initially the string str is initialize with the "ABC" then we add another string to the same variable str then it creates a new String "ABC XYZ", now this str variable will point to the "ABC XYZ" not to "ABC', but "ABC" is still in the memory but it is not referred to any variable. So when we modify any immutable class object then it will create a new object rather than modify the existing object.
 
Immutable classes are the thread safe because each time the modification made to the object the new object will be created, so in the mutithreaded environment, there is no worry about the thread safety.
 
We can also make our class to the immutable, for making the immutable class we have to do the following steps:-
 
1) Final Class:- Class must be final so that it can not be extended by other class.
 
2) Private member variable:- Restrict the direct access of member variables, we have to make them private.
 
3) No Setter methods: - Provide only getter method, to restrict the set member variables from outside the class.
 
4) Final Member Variable:- Make all the member variable final, So that it's value can be assigned only once.
 
5) Constructor:- Initialize all the member variables with the deep copy.
 
6) Cloning:- Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
 
So we can create the immutable class by following the above steps.Now the question arises in the mind that why immutable classes, what is the purpose of creating the immutable class. Immutable class provides many benefits that are the listed below:-
 
1.) Use Object in caching:- As we know that immutable object cannot change it's property so we can use the immutable object in the caching mechanism. Similarly, we can cache object's fields and also results of their methods.
 
2.) Thread Safety:- In Thread environment, we can use the immutable class object.Because multiple threads can access the same object but they can not change its properties.If they change then it will create a new object.
 
3.) Immutable object as Key in Map/Set:- Immutable object make best keys in Map and Set. If we use the mutable object as the key in HashSet and then object changes it's state then the HashSet implementation will become the confused,The object will present in the HashSet if we iterate it but  it may not appear if we check with contains() method of it, this will give the confusing behaviour of HashSet.Now understand this by example--
 
 
 
package com.lokhit.map;
import java.util.HashSet;
 
public class TestImmutable {
private String string;
 
public TestImmutable(String s) {
this.string = s;
}
 
public String getString() {
return string;
}
 
public void setString(String string) {
this.string = string;
}
 
public boolean equals(Object o) {
if (this == o)
return true;
else if (o == null || !(o instanceof TestImmutable))
return false;
else {
final TestImmutable other = (TestImmutable) o;
if (string == null)
return (other.string == null);
else
return string.equals(other.string);
}
}
 
public int hashCode() {
return (string != null ? string.hashCode() : 0);
}
 
public String toString() {
return string;
}
public static void main(String[] args) {
TestImmutable sh = new TestImmutable("Hitesh");
HashSet<TestImmutable> h = new HashSet<>();
h.add(sh);
sh.setString("Lokesh");
System.out.println(h.contains(sh));
System.out.println(h.size());
System.out.println(h.iterator().next());
}
}
 
Output:

false
1
Lokesh


In the above example, we can see that contains() method on HashSet return 'false' but the object is present when we iterate it so this is very confusing behavior. So we should always use the immutable object as a Key in HashMap as well in the Map. So this is all about the Immutable classes.

About Author

Author Image
Lokesh Kumar

Lokesh is a Software Developer having experience in Core Java, Hibernate, Struts, MongoDB. His interest includes playing chess,cricket,badminton.

Request for Proposal

Name is required

Comment is required

Sending message..