We know it pretty well – “String is immutable”
What does immutable mean?
If we go by dictionary, immutable means – “Unchanging over time or unable to be changed”
In other words, immutable means permanent.
Explanation from String Perspective
String in java is immutable because once a String object is created then the value of the object or state of the object cannot be changed over time. Object that is created is permanent.
We will consider an example for clarity.
String name = "Rajneesh";
String name = "Rajneesh" + "Shukla";
In the above scenario, I have created a String literal "Rajneesh". A String object “Rajneesh” is created and stored in the String constant pool, if it doesn’t already exist there. The object has reference to the variable name.
In the very next line, I am trying to concatenate “Shukla” to the previously created object “Rajneesh”.
What will happen next?
In the second line, a new object will be formed with value “RajneeshShukla”. And this object will also be stored in the String constant pool, if it doesn’t already exist there.
In String constant pool we will have two String objects by now. One is Rajneesh and another is RajneeshShukla.
Now our name variable will have reference to String object RajneeshShukla instead of Rajneesh.
Thus we can clearly see how String that is once created remains unchanged. Any modification on given String results in formation of new String object.
String is immutable in java.
Reason behind making String immutable in java
To improve the security of the application→ As we know that String objects are used as key in Maps, as database connections, as passwords and others. If String were mutable then these keys, connections, etc. could have been easily modified.
This would have a severe impact on our java application.
For example, say we have a String object "myPassword".
This object is being refered by various reference variables. Now suppose any one of these variable changes the value of this object to, say "Password", then all other reference variable would get impacted.
This is the reason for making String object immutable in java.
How operation on String is performed if it is immutable?
If such need arises then java provides us with facility of String Buffer and String Builder which helps us create mutable String. Use any one of them to create mutable String and keep modifying the characters of mutable String object.
In the next tutorial we will study in detail about both of them.