DEV Community

Cover image for IMMUTABILITY
Rini Simon
Rini Simon

Posted on • Updated on

IMMUTABILITY

Let’s see what this fancy word means.

immutable
adjective
unchanging over time or unable to be changed.

Umm...

How does STRING do it?

String strOne = "sun";

Simple as it is, created a String "sun" and assigned a reference i.e. strOne.
alt text
Now,

String strCopy = strOne;

Assigned another reference to "sun" i.e. strCopy.
alt text
So far looks good.....Let’s do another step

strOne = strOne.concat("flower");

This appends String "flower" to strOne.

alt text

But, WAIT!
What about immutability (you can’t change the string objects)?

Here is what happens
When this statement is executed, the VM takes the String “sun” and appends "flower", resulting in "sun flower".
Since String is immutable, the VM creates new String object, gives it the value “sun flower” and gives it a reference strOne.

alt text

Note:
Remember, the String objects are immutable but not the reference variable, that’s why we were able to reference the new object with the existing variable.

Okay,

Right now, we have two objects that we see "sun" pointed by strCopy and "sun flower" pointed out by strOne.
But technically, we have three. The third one being the literal "flower" from our concat statement.

alt text

Important Fact:
What if we dint have a reference to "sun"?
It still exists but, it’s lost because there is no reference to it.

Okay, let’s try this

String one = "learn";
one.concat("java");
system.out.prinln("one refers to:" + one); 

What do you see? Surprised?

First line creates a new String "learn" gives it a reference one, simple.
Second line the VM creates a new String "learn java" but it has no reference. Hence, we can’t reach out to it and consider it lost. The reference variable one still refers to "learn".

Almost, every time a method tries to modify a String object, it creates a new String object.

What happens to all these objects? Where are they?
They exist in memory.

The JVM sets aside some memory called the “Spring Constant Pool”.
When the compiler gets a string literal it looks for it in the pool. If there is a match, the reference to the new literal is directed to the existing string, thus no new string object is created. The existing string object has one or more reference. This is how string objects are immutable.

Each String object in the string constant pool is likely to have one or more reference. If several references are point to one object without each of them knowing it, then it would be bad if any of the reference modified the value of the object, that is why string objects are immutable.

What if I override the string class functionality?
Well, you can’t. The String class is marked final so nobody can override its behavior.


I hope this was informative. Happy learning :D
photo by : Rini Simon

Top comments (0)