Answer one:
One of the most popular Java interview questions is: What is an immutable object (immutable object), what are the benefits of immutable objects, and under what circumstances should it be used? Or more specifically, why should Java's String class be set to an immutable type?
Immutable objects, as the name suggests, are objects that cannot be changed after creation. A typical example is the String class in Java.
Copy the code code as follows:
String s = "ABC";
s.toLowerCase();
As above, s.toLowerCase() does not change the value of "ABC", but creates a new String class "abc" and then points the new instance to the variable s.
Immutable objects have many advantages over mutable objects:
1). Immutable objects can improve the efficiency and safety of String Pool. If you know that an object is immutable, then when you need to copy the contents of the object, you don't need to copy it itself but just its address. Copying the address (usually the size of a pointer) requires very little memory and is very efficient. . It will not affect other variables that reference this "ABC" at the same time.
2). Immutable objects are safe for multi-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, and using immutable objects is This situation can be avoided.
Of course, there are other reasons, but the biggest reason why Java sets String to immutable is efficiency and safety.
Answer two:
This is an old yet still popular question. Designing String to be immutable in Java is the result of taking various factors into consideration. To understand this problem, you need to integrate memory, synchronization, and data. Structural and safety considerations. In the following, I will make a summary of various reasons.
1. The need for string constant pool
String constant pool (String pool, String intern pool, String retention pool) is a special storage area in Java heap memory. When creating a String object, if the string value already exists in the constant pool, it will not be created. A new object, but a reference to an existing object.
As shown in the following code, only one actual String object will be created in the heap memory.
Copy the code code as follows:
String s1 = "abcd";
String s2 = "abcd";
The schematic diagram is as follows:
If the string object is allowed to change, it will lead to various logical errors. For example, changing one object will affect another independent object. Strictly speaking, the idea of this constant pool is an optimization method.
Please think: If the code is as follows, will s1 and s2 still point to the same actual String object?
Copy the code code as follows:
String s1= "ab" + "cd";
String s2= "abc" + "d";
Maybe this question is counterintuitive to novices, but considering that modern compilers will perform regular optimizations, they will all point to the same object in the constant pool. Alternatively, you can use tools such as jd-gui to view the compiled class document.
2. Allow String objects to cache HashCode
The hash code of String objects in Java is frequently used, such as in containers such as hashMap.
String immutability ensures the uniqueness of the hash code, so it can be cached with confidence. This is also a performance optimization method, which means that there is no need to calculate a new hash code every time. There is the following code in the definition of the String class :
Copy the code code as follows:
private int hash;//used to cache HashCode
3. Security
String is used as a parameter by many Java classes (libraries), such as network connection address URL, file path, and String parameters required by the reflection mechanism. If String is not fixed, it will cause various security risks. .
If there is the following code:
Copy the code code as follows:
boolean connect(string s){
if (!isSecure(s)) {
throw new SecurityException();
}
// If String can be modified elsewhere, various unexpected problems/errors will occur here.
causeProblem(s);
}
Generally speaking, the reasons why String is immutable include design considerations, efficiency optimization issues, and security. In fact, this is also the answer to many "why" in Java interviews.
Answer 3: Benefits of String class immutability
String is the most commonly used class in all languages. We know that in Java, String is immutable and final. Java also saves a String pool at runtime, which makes String a special class.
Benefits of String class immutability
1. String pooling is only possible when strings are immutable. The implementation of the string pool can save a lot of heap space at runtime, because different string variables point to the same string in the pool. But if the string is variable, then String interning will not be possible (Translator's Note: String interning means that only one different string is saved, that is, multiple identical strings will not be saved.), because in this case , if a variable changes its value, the values of other variables pointing to this value will also change.
2. If the string is variable, it will cause serious security problems. For example, the username and password of the database are passed in as strings to obtain the database connection, or in socket programming, the host name and port are passed in as strings. Because a string is immutable, its value cannot be changed, otherwise hackers can exploit loopholes and change the value of the object pointed to by the string, causing a security vulnerability.
3. Because strings are immutable, they are multi-thread safe, and the same string instance can be shared by multiple threads. This eliminates the need to use synchronization due to thread safety issues. Strings themselves are thread-safe.
4. Class loaders use strings, and immutability provides security so that the correct class is loaded. For example, if you want to load the java.sql.Connection class, and this value is changed to myhacked.Connection, it will cause unknown damage to your database.
5. Because the string is immutable, the hashcode is cached when it is created and does not need to be recalculated. This makes strings very suitable as keys in Maps, and strings can be processed faster than other key objects. This is why the keys in HashMap often use strings.
The above is my summary of the benefits of string immutability.