The most important reason is security .
There will be many security risks if a malicious thread can get a link to a mutable string, which must be passed to a method that must check the string before it performs an important operation. It would be possible for the thread to change the string after checking it, and then the operation would be performed using a dangerous string.
Another reason why String is immutable in Java is to allow String to cache its hash code.
As mentioned above, the most important reason is thread safety and security .
Consider a scenario in a banking application for transferring money - the recipient's account number is defined in the line as "0789567345". If by mistake / intentionally it acc. number is changed, the money will go to the wrong account.
Another scenario is if someone changes the class name somewhere between processing, like ..
getClass().getName().subString(0, 5);
The class loader will just say "Class Not Found
Nomesh gajare
source share