Immutable String Java

Dictionary meaning of Immutable: Unchanging over time or unable to be changed.

Immutable String represents a unmodifiable or unchangeable object. I.e. State of the String object can not be changed. A new string will be created, if we try to change the string value.

Let us take the below code.

String str1 = "w3spoint";
String str2 = "w3spoint";

When the 1st statement executes, Java will check string pool and it will create one “w3spoint” literal as there is no such string literal present in the string pool. When 2nd statement executes, Java again checks whether “w3spoint” present in the string pool or not. As it is present because of 1st statement, no more literal will be created for “w3spoint” and both str1 and str2 reference variable will point to same literal.

But if we write the code like:

String str1 = "w3spoint";
String str2 = "w3spoint";

Then 3rd statement will not modify “w3spoint” literal, Java will create one more literal with modified value i.e. “”. Now str1 will point to “” and str2 will point to “w3spoint”. As you can see that existing literals will not be modified hence we can say that string objects are immutable or final.

Advantages of immutable strings

  • Java Runtime saves a lot of heap space because multiple string references can point to the same String literal.
  • Immutable objects are thread safe.
  • HashCode of immutable object is cached at object creation time. There is no need to calculate it again and again, which results into high performance. Immutability is the reason because of which String preferred as HashMap key.

Java interview questions on String Handling

Please follow and like us:
Content Protection by
togel situs toto situs togel situs toto situs toto agen togel situs togel situs togel togel situs togel resmi situs togel situs togel situs toto link togel togel online