String class is not a common class. It has a specific requirements and it is handled as special by both JVM Specification and Java Language Specification. Many language features depend on ability of String to represent constant text. The "side effect" of the immutability of Strings is that it makes the Strings cacheable using hash value. That improve the performance a great deal.
Also, the memory management of Strings is somewhat different than normal objects.
A lot of security risks would appear if a malicious thread could gain a reference to a mutable String, which is about to be passed into a method that has to validate the String before it performs an important operation. It would be possible for the thread to change the string after it was validated, and then the operation would be carried out using a dangerous String.
As mentioned above - the most important reason - security & thread safety.
Consider a scenario, in a banking application for money transfer - the beneficiary account number is defined in a string as "0789567345".
If by mistake/intentionally this acc. number is changed, money will go to a wrong account.
Another scenario - if someone change the class name anywhere between processing as ..
The Class loader will simply say 'Class Not Found'
Security and thread safety isn't a reason; it's two reasons. If you search the Ranch, you will find how to cheat and change the internal representation of a String object. So security can easily be breached like that. You would use a SecurityManager object to prevent such security breaches. So I don't think security is the principal reason for immutability.
You will find this sort of question is asked frequently; I have just done a search and found this, where you can see several old threads about "why are strings immutable?" It is worth looking at those again.
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.
Another important reason, that applies to various classes used as "value objects", is that when using Strings for member variables that are exposed via getter methods, if they were mutable you'd have to keep making defensive copies to avoid breaking encapsulation.
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop