The string provided by this StringBuffer class is modified. You can use StringBuffer when you know the character data is going to change. Typically, you use StringBuffers to dynamically construct character data.
There are three classes in Java that are responsible for character operations.
1.Character operates on a single character.
2.String operates on a string of characters. Immutable classes.
3.StringBuffer also operates on a string of characters, but it is a variable class.
String:
It's an object and not a primitive type.
It is an immutable object, once it is created, its value cannot be modified.
Any modification to an existing String object involves re-creating a new object and then saving the new value into it.
String is a final class, that is, it cannot be inherited.
StringBuffer:
It is a mutable object. When it is modified, the object will not be re-established like String. It can only be established through the constructor.
StringBuffer sb = new StringBuffer();
note: It cannot be paid via pay symbols.
sb = "welcome to here!";//error
After the object is created, memory space will be allocated in the memory and a null will be initially saved. To StringBuffer
When paying the value, you can use its append method.
sb.append("hello");
The above is an excerpt, common on the Internet, the following is my own added insights:
The address cannot be changed, but the length and content can be changed. The append() method is to append. When the reserved memory is exceeded, the memory is doubled.
Efficiency comparison: StringBuffer is higher than String. Because StringBuffer has reserved space and keeps appending, it only operates on one object. String cannot be modified, and objects can only be created repeatedly to achieve modification. ――If you frequently append, replace, modify, insert, or delete strings, it is best to use StringBuffer. If you must use String, you can use StringBuffer to call toString() to convert it to String.
My machine is pretty rubbish, and the result after executing it is:
String running time: 164593
------------------
StringBuffer running time: 31
Moreover, String has a contains method, but StringBuffer does not. Contains means including. Here you can recall the contains method.
The execution result is
true