Monday, 25 April 2016

Why String is immutable ?


In Java, Strings are handling in Pool format.

Example


String str1 = “xyz”;
This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like

String str2 = “xyz”;
Now, JVM will check in String Pool where there is same characters are available or not.

If two Strings are match the JVM will refer str1address to str2. Now the str1 and str2 referring the same characters insame memory location.
This is a good idea for increasing memory efficiency.

When we change the str1 characters, the changes will be reflected to str2, because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.

Making String immutable, makes it thread safe and thus improves performance.
Once a string object is created no changes can be made to it. If a string is modified in code a new object will be created.
That is why string is immutable.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.