Java saves a string pool at run time, which makes string a special class.
The benefits of the non-variability of the string class
(1) A string pool is possible only if the string is immutable. The implementation of a string pool can save a lot of heap space at run time, because different string variables point to the same string in the pool. But if the string is mutable, then string interning will not be implemented (translator Note: string interning refers to just one save for different strings, that is, not many of the same strings are saved.) Because then, if the variable changes its value, the value of the other variable that points to that value will change as well.
(2) If the string is mutable, it can cause serious security problems. For example, the user name and password of the database are passed in as strings to get a connection to the database, or in socket programming, the hostname and port are passed in as a string. Because the string is immutable, its value is immutable, otherwise hackers can drill into the empty, change the value of the object that the string points to, resulting in a security breach.
(3) Because strings are immutable, multithreading is secure, and the same string instance can be shared by multiple threads. This will not use synchronization because of thread-safety issues. The string itself is thread-safe.
The ClassLoader uses a string, and immutability provides security so that the correct class is loaded. For example, if you want to load the Java.sql.Connection class, and this value is changed to myhacked.connection, it will cause an unknown damage to your database.
(4) because the string is immutable, hashcode is cached when it is created and does not need to be recalculated. This makes the string well suited as a key in the map, and the string is processed faster than other key objects. This is where keys in hashmap tend to use strings.
Why is the string class immutable?