Why Strings are immutable in Java (Final Answer)

There are two ways to look at this:

1. Why immutable? 2. How to ensure immutable?Copy the code
1. Why is design immutable?
1.String objects are cached in the String pool. Since cached strings are shared among multiple clients, there is always a risk that one client's operation on a String object will affect other clients. For example, if a piece of code will String"Test"Is changed to"TEST", all other customers will also see the value. Because String cache performance is an important aspect, you avoid this risk by making the String class immutable. 2. Because strings are popular as HashMap keys. The most important thing about key values is that they are immutable, so that they can be used to retrieve value objects stored in the HashMap. Since HashMap works as a hash, it needs to have the same values for it to work. If the contents of the String are modified after insertion, the mutable String will generate two different values for insertion and retrievalhashCode that may lose the value object in the Map.Copy the code

2. How to make String immutable

1. With final modification, no one can break String class immutability, caching, hashing, etc., by extending and overwriting the behavior. 2. Guaranteed by parental delegationCopy the code