Why is Java's string class immutable

  • 2020-04-01 03:17:11
  • OfStack

Answer a:

One of the most popular Java interview questions is: what is an immutable object, what are the benefits of an immutable object, under what circumstances should it be used, or, more specifically, why should Java's String class be set to immutable?
Immutable objects, as the name implies, are objects that cannot be changed after creation. A typical example is the String class in Java.

 
String s = "ABC";  
s.toLowerCase(); 

Instead of changing the value of "ABC", s.tbowercase () creates a new String class "ABC" and points the new instance to the variable s.
Immutable objects have many advantages over mutable objects:
1). Immutable objects can improve the efficiency and security of String Pool. If you know that an object is immutable, then when you need to copy the object's contents, you don't need to copy the object itself but just its address. Copying the address (usually the size of a pointer) requires very little memory and is very efficient. There is no effect on other variables that reference this "ABC" at the same time.
2). Immutable objects are safe for multiple threads, because when multiple threads are running at the same time, the value of a mutable object is likely to be changed by other processes, which will cause unpredictable results, which can be avoided by using immutable objects.
There are other reasons, of course, but the biggest reasons Java makes String immutable are efficiency and security.


Answer 2:

This is an old yet still popular question. The design of String as immutable in Java is the result of comprehensive consideration of various factors. To understand This problem, it is necessary to integrate memory, synchronization, data structure and security considerations.

1. Need for string constant pool

String pool (String intern pool, String reserved pool) is a special storage area in the Java heap memory. When a String object is created, the pseudo-string value already exists in the constant pool, then a new object is not created, but an existing object is referenced.
As shown in the following code, only one actual String object will be created in heap memory.


String s1 = "abcd";  
String s2 = "abcd";  

The schematic diagram is as follows:
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / img.jbzj.com/file_images/article/201404/201441792454086.jpg? 20143179257 ">  

If the string object is allowed to change, then it will cause various logic errors, such as changing one object will affect another independent object.

Think: if the code looks like this, would s1 and s2 still point to the same actual String object?


String s1= "ab" + "cd";  
String s2= "abc" + "d";  

This may seem counterintuitive to the novice, but considering that modern compilers do regular optimizations, they all point to the same object in the constant pool, or you can use a tool like jd-gui to look at the compiled class file.

2. Allow String objects to cache HashCode

The hash code for String objects in Java is used frequently, for example in containers such as hashMap.

String invariance guarantees the uniqueness of the hash code, so it can be cached safely.


private int hash;//Used to cache HashCode 

3. The security

String is used by many Java classes (libraries) as parameters, such as network connection address URL, file path, and String parameters required by reflection mechanism, etc. If String is not fixed, it will cause various security risks.
Suppose you have the following code:


boolean connect(string s){
    if (!isSecure(s)) { 
throw new SecurityException(); 
}
    //If strings could be modified elsewhere, there would be all kinds of unexpected problems/errors here
    causeProblem(s);
}

In general, there are three reasons why String is immutable: design considerations, efficiency optimization, and security.


Answer 3: the benefits of String class invariability

String is the most commonly used class in any language. We know that in Java, String is immutable and final. Java also holds a String pool at runtime, which makes String a special class.

The benefits of String class invariability

1. String pooling is possible only if the string is immutable. An implementation of a string pool can save a lot of heap space at run time because different string variables all point to the same string in the pool. But if strings are mutable, then String interning will not work. Because in that case, if the variable changes its value, then the values of other variables pointing to that value will change as well.
2. If strings are mutable, this can cause serious security problems. For example, the username and password of the database are passed in as a string to get the connection to the database, or in socket programming, the host name and port are passed in as a string. Because a string is immutable, its value is immutable, otherwise hackers can exploit the gap and change the value of the object to which the string is pointing, creating a security hole.
3. Because strings are immutable, they are multithreaded safe, and the same string instance can be Shared by multiple threads. This eliminates the need for synchronization because of thread-safety issues. Strings themselves are thread-safe.
4. Class loaders use strings, and immutability provides security so that the correct classes are loaded. For example, if you want to load the java.sql.connection class and the value is changed to myhact.connection, it will cause unknown damage to your database.
5. Because the string is immutable, hashcode is cached when it is created and does not need to be recalculated. This makes strings ideal for keys in maps, which are processed faster than other key objects. This is why keys in a HashMap tend to use strings.
So that's my summary of the benefits of string invariance.


Related articles: