Why String is immutable in Java?

Why are Strings immutable in Java?

String is immutable in Java. An immutable class means that its instance cannot be modified after it is created. All properties of the instance are initialized at creation time and cannot be modified later. Immutable types have many advantages. This article summarizes why strings are designed to be immutable, and explains the concept of immutability from the perspective of memory, synchronization, and data structures.

1 String pool needs

A string pool is a special memory area that exists in the Java method area, and when the target string to be created already exists in the string pool, the string reference in the string pool is returned and assigned to the target string, rather than creating a new object.

The following code creates only one object in the heap:

String string1 = "abc";
String string2 = "abc";
Copy the code

Graphical representation:

2 is used as a hashcode for caching

String hashes are frequently used in Java. For example, in a HashMap or HashSet, String immutability guarantees that the String hashCode is consistent, so you don’t need to worry about String changes when caching, which means that you don’t need to evaluate the String hashcode every time it’s used to ensure consistency. It’s more efficient.

In the String class source code there is the following code:

    /** Cache the hash code for the string */
    private int hash; // Default to 0
Copy the code

3 Facilitate the use of other objects

Concretely, consider the following code:

HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));
for (String s : set){
    a.value = "a";
}
Copy the code

In this example, if a String is mutable, its value can be changed, but this violates the design principle of a Set (elements in a Set cannot be repeated). Of course, the above example is just for purpose. There is no value member in the String class.

Four security

String is widely used as an argument in Java, for example, to connect to a network, open a file, etc. If String is designed to be mutable, then a network connection or file operation can be changed, which can leave a very serious security risk. The expected result of the method call is a successful connection to the device, which may not be the case. Mutable strings can also cause security issues in reflection because the arguments are strings.

Code examples:

boolean connect(String str){
    if(! isSecure(str)){throw new SecureException();
    }
    // A problem occurs if the value of STR is changed by another reference object before the method is called.
    caseProblem(str);
}
Copy the code

Immutable objects are inherently thread-safe

Because immutable objects cannot be changed, they can be freely accessed across multiple threads. This eliminates the need to synchronize access.

In summary, the reason strings are made final is for efficiency and security, and in general this is why immutable objects are preferred in many designs.


Related articles:
  • Create Java String Using “” or Constructor?
  • Diagram to show Java String’s Immutability
  • Top 10 questions of Java Strings
  • LeetCode — Reverse Words in a String (Java)
  • Java method area