The same point : both are related to string operations (all implements CharSequence), and the bottom layer is all char [ ] to store data.
String: immutable sequence of characters;
StringBuffer: variable character sequence; thread-safe, inefficient;
StringBuilder: variable character sequence; thread unsafe, high efficiency (new in jdk5.0);
The immutability of String is as follows: ① Add a string after the current string, and recreate a new string in the constant pool.
②Modify the existing string and re-create a new string in the constant pool.
String str = new String("abc"); // new char [ ] {'a','b','c'}. Fixed-length array.
String source code:
String's immutability Reason: The char[] array defined in the underlying code is decorated with final.
StringBuffer/StringBuilder variable reason is: both inherit (extends) AbstractStringBuilder, the char [ ] defined by AbstractStringBuilder has no modifier.
StringBuffer sb1 = new StringBuffer ( ); // new char [16 ] By default, the parameterized constructor of the parent class is called, and the parameter is 16
sb1.length(); //0
sb1.append("a"); // char[0] = 'a'
sb1.append("b"); // char[0] = 'b'
.......
It is possible to go beyond the scope of the underlying data: problems involving expansion (implemented in AbstractStringBuilder).
default int newCapacity = value.length * 2 + 2;
Data copy after expansion: value = Arrays.copyOf(value, newCapacity);
Development suggestion: When the length of the string is known, the definition directly specifies the length of the array.
The source code part shows:
AbstractStringBuilder
StringBuilder
StringBuffer