Why string is immutable?

String in a class it is used to holding the array of characters. The difference between String and StringBuffer is String is immutable where as StringBuffer is mutable. Means we can not change the value of the string.

Why it so?

Actually in java, Strings are handling in Pool format.

For 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 str1 address to str2. Now the str1 and str2 referring the same characters in same 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.

17 thoughts on “Why string is immutable?

  1. Very impressive answer dude and Useful also..

    But explain with example are Give Clearly idea about It. …so dude exaplain with example….

Leave a comment