The differences are as follows:
1) Once the content of the String class is declared, it cannot be changed. What changes is only its memory pointer, while the object content of the StringBuffer class is Can be changed.
2) For StringBuffer, object instantiation cannot be completed directly through assignment like String, but must be completed through the constructor method.
3) StringBuffer does not generate new objects when processing strings, and is better than the string class in terms of memory usage. Therefore, in actual use, if you often need to modify a string, such as insertion, deletion and other operations, it is more suitable to use StringBuffer.
Online teaching video sharing: java video
Example: String object cannot be modified means that the object itself cannot be modified, not that the reference cannot be modified.
String a = “你好”;
This line of code means to declare a String type reference variable called a, create a String object in memory (with a value of "Hello"), and then assign the reference of this object to the variable a.
a = “hello”;
The effect of this line of code is to create another String object (with a value of "hello") in the memory, and then assign the reference of this new object to the variable a, instead of assigning the original string object to the memory. The String object value of "hello" becomes "hello".
4) The biggest difference between StringBuilder and StringBuffer is that the methods of StringBuilder are not thread-safe (cannot be accessed synchronously).
5) StringBuilder has a speed advantage compared to StringBuffer, so it is recommended to use the StringBuilder class in most cases. However, when the application requires thread safety, the StringBuffer class must be used.
If you want to know more java related articles, you can visit: Introduction to java programming
The above is the detailed content of The difference between String, StringBuffer and StringBuilder in java. For more information, please follow other related articles on the PHP Chinese website!