Why is immutability important in Java?
What is immutability
Immutability is when you cannot modify an object created.
Strings in Java are said to be immutable. However, a String variable created can be changed to another variable. What’s up with that?
Say for example you have a variable named name.
String name= “John”;
Behind the scenes, a new object is created. The value of the variable name is changed (dereferenced from John and referenced to Jane). However, the created object “John” is still lying inside the Heap as below.
Assume the above scenario.
It has 3 different variables with the same value. If the saving of value “John” takes 4 bytes for allocation, it should take 3 x 4 bytes for the whole about scenario to take place.
But instead, Java uses a mechanism called String pools allowing to achieve the performance efficiency with its most common data type.
This can be proven by using the == operation as follows. This is because the == operation only compares the reference of the variable.
print(name==person); //prints true
print(name==employee); //prints true
print(person==employee); //prints true
new String Object
However, using new String(“John”) to explicitly create a new String object is a different case.
String cricketer=new String(“John”);
The Object would be created outside the String pool which makes the object not to pass the above if condition.
print(name==cricketer); //prints false
So simply put, Java is able to save space by the following the String pool mechanism.
Lets look at another scenario.
name=”Jane”; //referenced from John and referenced to Jane
This is how the memory allocation would look like.
Say you have a method named as doIt() that is passed the above variable name as a parameter. But meantime you did the above modification (from “John” to “Jane”), this would impact the entire process.
//some modifications to the object
Java has different mechanisms (pass by value(P/V), pass by reference (P/R), immutability) to overcome these kinds of problems (thread safety). But that’s a topic for another day!
Thanks for reading! Until next time. 👋🏽