1. Why is String immutable?
A brief description: This can be seen in the JDK source code. String is essentially a char[] array. And with final modification, in JDK1.7, there are mainly two member variables of String.
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** String本质是个char数组. 而且用final关键字修饰.*/
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
....
....
Final modified char[] array, the reference is immutable , although the reference is immutable. That doesn't stop the fact that Array arrays are mutable. The data structure of Array is shown in the figure below
final int[] value={1,2,3}
int[] another={4,5,6};
value=another; //编译器报错,final不可变
The value is decorated with final, and the compiler does not allow us to point the value to another address in the heap area. But if I do it directly on the array elements, it will be done in minutes.
final int[] value={1,2,3};
value[2]=100; //这时候数组里已经是{1,2,100}
However, the char array is defined as private in the source code, and the private members cannot be accessed and changed externally. So in summary String is immutable.
For a detailed analysis, see
① Why is String in Java immutable? – String source code analysis
② How does Zhihu understand the immutability of String type values?
2. How many objects are created by String s=new String("abc")?
① How many objects does String s=new String(“abc”) create?
② String str = new String(“abc”); How many objects are created in the interview questions
③ String a = new String(“abc”) in Java ;Will this create objects abc in the heap and stack respectively?
④ Please don't take "String s = new String("xyz"); How many String instances are created" for the interview?
3. String class and constant pool
① Java constant pool understanding and summary
② Why does Java need constant pool
③ String constant pool in Java
4. Is the concatenation of String + operator overloading?
① Java details: concatenation of strings
② Why does Java not support operator overloading?
③ JAVA syntactic sugar "+" operator
5. What is the difference between String, StringBuilder and StringBuffer?
① String: The functional difference between String / StringBuffer / StringBuilder
② The difference between String, StringBuilder and StringBuffer in Java