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 = "w3schools"; String str2 = "w3schools"; |
When the 1st statement executes, Java will check string pool and it will create one “w3schools” literal as there is no such string literal present in the string pool. When 2nd statement executes, Java again checks whether “w3schools” present in the string pool or not. As it is present because of 1st statement, no more literal will be created for “w3schools” and both str1 and str2 reference variable will point to same literal.
But if we write the code like:
String str1 = "w3schools"; String str2 = "w3schools"; str1.concat(".com"); |
Then 3rd statement will not modify “w3schools” literal, Java will create one more literal with modified value i.e. “w3schools.com”. Now str1 will point to “w3schools.com” and str2 will point to “w3schools”. 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
- Why string objects are immutable in java?
- How many ways we can create the string object?
- Why java uses the concept of string literal?
- What is the basic difference between string, stringbuffer and stringbuilder object in java?
- How to create immutable class in java?
- What is the purpose of toString() method in java?
- Is string a keyword in java?
- Is string a primitive type or derived type?
- What is string constant pool in java?
- What are mutable and immutable objects in java?
- What is string intern in java?
- Can we call string class methods using string literals?