Why the String class in Java is immutable (detailed explanation)
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[];}
The value of the String class is stored in in the value array, and is modified by private final
1. Private modification indicates that external classes cannot access value, and subclasses cannot access it. Of course, the String class cannot have subclasses. , because the class is final modified
2, final modification, indicating that the reference of value will not be changed, and value will only be initialized in the constructor of String, and there is no other way to modify the value in the array Value ensures that the reference and value of value will not change
So we say that the String class is immutable.
And many methods, such as substring, do not operate on the original String class, but generate a new String class
public String substring(int beginIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } int subLen = value.length - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);}
Why is String set to be disabled? changing?
String constant pool
Java has 8 basic data types
Integer types: byte, short, int, long. Packaging types are Byte, Short, Integer, Long
Floating point types: float, double. The packaging type is Float, Double
Character type: char. The packaging type is Character
Boolean type: boolean. The packaging type is Boolean
Except Float and Double among the 8 packaging types, the constant pool is not implemented. The rest are implemented. Of course, they are all constants of the String class implemented through the flyweight mode. Pools are implemented at the JVM level.
Why is there a constant pool? The constant pool is used to avoid frequent creation and destruction of objects that affects system performance, and it implements object sharing.
For example, the string constant pool puts all string literals into a constant pool during the compilation phase.
I will not discuss anything before jdk1.7. Starting from jdk1.7, the string constant pool began to be placed in the heap, and then all the contents of this article are based on jdk1.8
The following code is often asked
String str1 = "abc"; String str2 = "abc"; String str3 = new String("abc"); String str4 = new String("abc"); // trueSystem.out.println(str1 == str2); // falseSystem.out.println(str1 == str3); // falseSystem.out.println(str3 == str4);
The constant pool stores references
Explain the output of the above code. There are two ways to create string objects in Java
String str1 = "abc"; String str2 = "abc"; // trueSystem.out.println(str1 == str2);
When creating a string using a literal value, the JVM will first remove the string Find whether the object "abc" exists in the pool
If it does not exist, create the object "abc" in the string pool, and then assign the address of the object "abc" in the pool to str1, so that str1 It will point to the string object "abc" in the pool
If it exists, no object will be created, and the address of the "abc" object in the pool will be directly returned and assigned to str2. Because str1 and str2 point to the "abc" object in the same string pool, the result is true.
String str3 = new String("abc"); String str4 = new String("abc"); // falseSystem.out.println(str3 == str4);
When using the new keyword to create a string object, the JVM first searches for the string object "abc" in the string pool.
If not, it first searches the string object in the string pool. Create an "abc" string object in the pool, then create an "abc" string object in the heap, and then assign the address of the "abc" string object in the heap to str3
If there is one, Then instead of creating the "abc" object in the pool, create an "abc" string object directly in the heap, and then assign the address of the "abc" object in the heap to str4. In this way, str4 points to the "abc" string object created in the heap;
Because str3 and str4 point to different string objects, the result is false.
Cache HashCodeWhen the String class is created, the hashcode is cached in the hash member variable because the String class is immutable , so the hashcode will not change. In this way, every time you want to use the hashcode, you can just get it directly without recalculating it, which improves the efficiency.
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** Cache the hash code for the string */ private int hash; // Default to 0 }
Can be used as the key of HashMapDue to the immutable nature of the String class, it is often used as the key of HashMap. If the String class is variable and the content changes, the hashCode will also change. When fetching it from the HashMap based on this key, it may not be fetched. value, or get the wrong value
Thread safetyImmutable objects are inherently thread-safe, which can avoid problems in a multi-threaded environment Next, perform synchronization operations on String.
Thank you everyone for reading, I hope you will benefit a lot.
This article is reproduced from: https://blog.csdn.net/zzti_erlie/article/details/106872673
Recommended tutorial: "java tutorial"
The above is the detailed content of Why is the String class in Java immutable (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!