[Simple Java] Why is the string in Java unchangeable? simplejava
In Java, a string is an immutable class. An Immutable class indicates that its instance object cannot be modified. All information about this object has been initialized when this object is created and cannot be modified. Immutable classes have many advantages. This article summarizes the reasons why strings are designed as immutable classes. A reasonable explanation depends on a deep understanding of the memory model, synchronization, and data structure.
Requirement for String constant pool
The String constant pool is a special storage area in the method area. When you need to create a string, if its value already exists in the String constant pool, the string reference in the constant pool will be directly returned, instead of creating a new String object, return its reference.
String string1 = "abcd";String string2 = "abcd";
If the string is variable, a reference is used to change the value of the string, and other references to the string object will get the wrong value.
Cache Hashcode
The hashcode of a string is often used in java, such as HashMap. Immutable, The hashcode will always be the same, so it can be cached without worrying about changes. This also means that the hashcode does not need to be re-computed every time the String is used, which makes the performance more effective.
In the String class, a hash field is used to cache the hash code.
private int hash;//this is used to cache hash code.
Convenient use of other objects
For more details, see 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 variable, its value will be changed, which will violate the design of the Set (repeated elements are not allowed ). Of course, this is just an example. Actually, String does not have a value field.
Security
Strings are widely used as parameters, such as network connections and file opening operations. If the string is variable, the network connection or file will be changed, which will cause serious security threats. A method is considered to be connected to a machine, but it is changed and connected to another machine. In reflection, a variable string also causes security problems because the parameter is also a string.
The following code is an example:
boolean connect(string s){ if (!isSecure(s)) { throw new SecurityException();} //here will cause problem, if s is changed before this by using other references. causeProblem(s);}
Immutable object inherent thread security
Because immutable objects cannot be modified, they can be shared by multiple threads, which eliminates synchronization operations.
In general, strings are designed to be immutable for performance and security considerations, Which is why immutable classes are more popular.
Http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/.