Transfer from http://developer.51cto.com/art/201503/468905.htm
This article mainly introduces the immutable objects in Java, and the immutability of the string class in Java, so why is the Java String class immutable? Let's analyze it together.
Answer one:
One of the most popular Java surface questions is: What are immutable objects (immutable object), what are the benefits of immutable objects, what situations should be used, or more specifically, why is the Java string class set to immutable type?
Immutable objects, as the name implies, can not be changed after the creation of objects, a typical example of Java is the string class.
String s = "ABC"
As above s.tolowercase () does not change the value of "ABC", but instead 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 security of the string pool. If you know that an object is immutable, then you need to copy the object's contents without copying it itself and just copying its address, and copying the address (usually a pointer size) requires very little memory efficiency. Other variables that also refer to this "ABC" are not affected.
2). Immutable objects are safe for multithreading because, in the case of multithreading, the value of a mutable object is likely to be changed by other processes, which can result in unpredictable results, and the use of immutable objects avoids this.
There are other reasons, of course, but the biggest reason why Java sets string to immutable should be efficiency and security.
Answer two:
It's a cliché topic (this is a old yet still popular question). In Java, the design of string as immutable is to take into account the results of various factors, to understand the problem, need to integrate memory, synchronization, data structure and security considerations. In the following, I will make a summary for various reasons.
1. The need for a string constant pool
The string Chang (string pool, string intern pool, string reserve) is a special storage area in Java heap memory, and when a string object is created, a new object is not created if the string value already exists in the constant pool. Instead, it refers to an already existing object.
As shown in the following code, only one actual string object will be created in heap memory.
String S1 = "ABCD"
As shown below:
Think: If the code looks like this, will S1 and S2 point to the same actual string object? If the string object is allowed to change, it will cause various logic errors, such as changing one object to affect another independent object. Strictly speaking, the idea of this constant pool is an optimization method.
String s1= "AB" + "CD"; String S2
Perhaps this is a violation of the novice's intuition, but given that the modern compiler will perform regular optimizations, they will point to the same object in the constant pool. Alternatively, you can view the compiled class file with a tool such as Jd-gui.
2. Allow string objects to cache Hashcode
Hash codes for string objects in Java are used frequently, such as in containers such as HashMap.
String invariance guarantees the uniqueness of the hash code, so you can cache it with confidence. This is also a performance optimization tool, meaning that you do not have to calculate a new hash code every time. The following code is in the definition of the string class:
private int hash;//is used to cache hashcode
3. Security
String is used by many Java classes (libraries) as parameters, such as the network connection address URL, file path, and the reflection mechanism required by the string parameter, if the string is not fixed, it will cause a variety of security risks.
If you have the following code:
Boolean Connect (string s) { if (! Issecure (s)) { thrownew SecurityException (); } // Causeproblem (s);
In general, the reasons for the immutable string include design considerations, efficiency optimization issues, and security in the three main areas. In fact, this is also the answer to many "why" in the Java interview.
Answer three: The benefits of the string class immutability
String is one of the most commonly used classes in all languages. We know that in Java, string is immutable and final. Java also saves a string pool at run time, which makes string a special class.
The benefits of the non-variability of the string class
1. String pooling is possible only if the string is immutable. The implementation of a string pool can save a lot of heap space at run time, because different string variables point to the same string in the pool. But if the string is mutable, then string interning will not be implemented (translator Note: string interning refers to just one save for different strings, that is, not many of the same strings are saved.) Because then, if the variable changes its value, the value of the other variable that points to that value will also change.
2. If the string is mutable, it can cause serious security problems. For example, the user name and password of the database are passed in as strings to get a connection to the database, or in socket programming, the hostname and port are passed in as a string. Because the string is immutable, its value is immutable, otherwise hackers can drill into the empty, change the value of the object that the string points to, resulting in a security breach.
3. Because the string is immutable, multithreading is secure, and the same string instance can be shared by multiple threads. This will not use synchronization because of thread-safety issues. The string itself is thread-safe.
4. The ClassLoader uses a string, 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 an 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 the string well suited as a key in the map, and the string is processed faster than other key objects. This is where keys in hashmap tend to use strings.
The above is my summary of the Java string immutability benefits, I hope to help you.
Why is the Java string immutable?