Original link: https://www.programcreek.com/2013/04/why-string-is-immutable-in-java/
The Java string is immutable. The immutable class is just a class that cannot modify an instance. All information is initialized when the instance is created, and the information cannot be modified. Immutable classes have many advantages. This article summarizes why a string is designed to be immutable. This illustrates the concept of invariance in terms of memory, synchronization and data structures.
1. String Pooling requirements:
A string pool (a string-specific pool) is a special storage area in a method area. When a string is created, if the string already exists in the pool, a reference to the existing string is returned instead of creating a new object.
The following code creates only one string object in the heap:
String string1 = "ABCD"; String string2 = "ABCD";
:
If the string is mutable, changing the string with a reference causes the value of the other reference to be incorrect.
2. Cache Hashcode:
In Java, the hashcode of strings is often used. For example, in a HashMap or hashset. The invariable guarantee Hashcode is always the same so it can be cashed without worrying about change. This means that you do not need to calculate hashcode every time you use it. This is more effective.
In the string class, it has the following code:
private int hash;//this is used to cache hash code.
3. Use other objects frequently:
To illustrate this issue, consider the following procedure:
hashset<string> set = new Hashset<string> (), Set.add (New string ("a")), Set.add (new string ("B")), Set.add ( New String ("C")); for (String a:set) A.value = "a";
In this example, if the string is mutable, its value can be changed, and the design set (including non-repeating elements) will be violated. Of course, the above example is for illustrative purposes only, and there is no value field in the real string class.
4. Security:
Strings are widely used in many Java class parameters, such as network connections, open files, strings, etc. are not immutable, a connection or file will be changed, which can lead to serious security threats. The method thinks it is connected to a machine, but not. Mutable strings can also cause security problems in reflection, because parameters are strings.
The code is as follows:
Boolean connect (string s) { if (!issecure (s)) {throw new SecurityException ();} Here would cause problem, if s is changed before this by using the other references. Causeproblem (s);}
5. Immutable objects are naturally thread-safe:
Because immutable objects cannot be changed, they can be freely shared among multiple threads. This eliminates the need for synchronization.
In summary, strings are immutable for efficiency and security reasons. This is why in many cases the preferred class is the immutable class.
Why are strings in Java immutable?