Tekchand Prasad wrote: Another reason of Why String is immutable in Java is to allow String to cache its hashcode.
I can well imagine a mutable class that would cache the hashcode and just mark it on every modification of its contents to be recalculated on next request. (By the way, if the hashcode of a
String happens to be 0, which it does even for some ordinary strings, it is in effect not cached and is recalculated on every call.)
I'll throw in another consideration: using mutable Strings as keys in a map would be very error prone. Though maps
could be modified to support mutable keys in general (mutable
and cloneable objects actually, it gets more muddy every time I think about it), it would incur serious memory and performance penalty.