How are Java Strings immutable
You might have heard a lot about Java Strings being immutable. You might have also faced interview questions where you are asked to explain this. In this blog post, I will be shedding some light on this with examples.
So yes, Java Strings are indeed immutable. So what does immutable mean? It means that String objects are constants, their values cannot be changed after they are created.
Now consider the following code:
String str= "abc";str= "xyz";
Is the above code valid?
Yes, the above lines are perfectly valid. Now this might appear confusing to a new programmer because we are changing the value of “str” from “abc” to “xyz“. But that is not so.
The object “abc” remains as it is and a new object “xyz” is created. The object reference “str” no longer points to the memory address of “abc“, but it points to the address of “xyz“. And what about “abc“? It continues to exist as it is until it is garbage collected.
The following diagram depicts this scenario. In Figure 1, the variable “str” points to the String “abc” whereas in Figure 2 the variable “str” points to the String “xyz” but the String “abc” still exists in memory.
Comments
Post a Comment