What's the advantage of a String being Immutable?

Viewed 15368

Once I studied about the advantage of a string being immutable because of something to improve performace in memory.

Can anybody explain this to me? I can't find it on the Internet.

7 Answers

a) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say String A = "Test" and String B = "Test" Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
b) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hash code and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key.

Related