Immutable String
class StringTutorial { public static void main(String args[]) { String s="Robert"; s.concat("James");//Using concat function to Add "James" at the end of "Robert" System.out.println(s);//will print Robert because strings are immutable objects and original state cannot be changed! } }
Output:
Robert
In the above example, we are trying to add the string "James" at the end of "Robert". After we have used concat function to add the two Strings the output is surprisingly still the same.Why did it happen?
It happened because String objects are immutable and cannot be changed and 's' represents a String object holding the value "Robert".Whatever changes we make to the content of 's' will not be reflected in it instead a new object will be created in memory containing the changes we wanted to do and the reference variable 's' will be made to point to that new object.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhK8isdl2k0J8fCkhA44-ox6DrPajSlXzjTt-H2-uk8UgDCXaeers4UefvHNeyv5lsfbZA7NE3l7c-c85yxio6ybyumJbDb0RScB_9ZhKXBRjNH-KAehRTbx92ATKPkEt1kC_XQH831Fbis/s640/string_immutable.png)
Here 's' was pointing to "Robert" and when we used the concat function to add "James" at the end of "Robert" the original object was not affected but a new object was created with the changes we wanted.
Did you notice that 's' is still pointing to the old object? and this is the reason why the output was still "Robert" not "RobertJames" because we forgot to make 's' point to the newly created object.If we want the concatenated output then we should do this
class StringTutorial { public static void main(String args[]) { String s="Robert"; s=s.concat("James");//Using concat function to Add "James" at the end of "Robert" System.out.println(s);//will print RobertJames } }
Why Strings are Immutable in Java?
The exact reasons for making strings immutable in java can be stated only by the the creators of String class.There can be many possible answers to this question but let's see some reasonable arguments :
1)Required by String constant pool:
String pool is a special storage area in Java heap memory. Whenever a string is created and that newly created string already exists in the String constant pool, the reference of the existing string will be returned and assigned to the reference variable associated with the new string, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap
String string1 = "Hello"; String string2 = "Hello";
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdawLysestPm82kU1mSvuMVYsOXHmbyEI2ipYT6AgiDDj-TY4tFbyTC4SaWLwz0RzJ5o7hcFeYuS0GsCJuM-KFPdNb7I-Ale8QCLzf5J3Wktku82E55xMs-xf1w8D5V81t8qUTr-Y7rW0a/s400/string_pool.png)
If string is not immutable, changing any one string will lead to the wrong value for the other references.
2)Security:
3)To make Strings thread-safe:
4)Caching hashcode:
5)Class Loading Mechanism:
No comments:
Post a Comment