In Java, strings are string constants that can be analyzed in terms of memory, synchronization mechanism, data structure, etc.
1: Need for constant pool in string
The place where a string differs from the common base variable type is the object. String objects in Java are stored in a string constant pool, and when you create a string, you first look for the same string object from the constant pool, and the new string object is created without being present.
If the string is designed to be mutable, there is a potential risk of affecting the other same object that points to the constant pool while modifying a string.
2:hashcode Cache
In a hashmap or hashset data structure, storing a string is often a hash value, and a string immutable feature guarantees the uniqueness of the hash and avoids a hash-causing conflict. It is also not necessary to repeatedly compute the hash value every time a string object in the collection is used, high efficiency.
3: Thread Safety
The immutability of string refers to the ability to share after different threads, while ensuring thread safety and helping developers reduce thread synchronization.
Of course, different scenarios can have different characteristics.
Why does Java design string immutable (immutable)