In Java, String, StringBuffer, and StringBuilder are often used string classes in programming. The difference between them is also a question that is often asked in interviews. Now summarize and see how they are different and the same.
1. Variable and immutable
String class uses a character array to save strings, as follows: Because there is a "final" modifier, you can know that string objects are immutable.
private final char value[];
Both StringBuilder and StringBuffer are inherited from the AbstractStringBuilder class. In AbstractStringBuilder, character arrays are used to save strings. As follows, it can be seen that both objects are mutable.
char[] value;
2. Is it multi-threaded and safe
Objects in String are immutable, so they can be understood as constants, which are obviously thread-safe.
AbstractStringBuilder is a public parent class of StringBuilder and StringBuffer, which defines some basic operations of strings, such as expandCapacity, append, insert, indexOf and other public methods.
StringBuffer has added a synchronization lock to the method or a synchronization lock to the called method, so it is thread-safe. See the following source code:
public synchronized StringBuffer reverse() { super.reverse(); return this;}public int indexOf(String str) { return indexOf(str, 0); //There is a public synchronized int indexOf(String str, int fromIndex) method}StringBuilder does not add synchronization locks to the method, so it is non-thread-safe.
3. StringBuilder and StringBuffer in common
StringBuilder and StringBuffer have public parent classes AbstractStringBuilder ( abstract class ).
One of the differences between abstract classes and interfaces is that some public methods of subclasses can be defined in abstract classes. Subclasses only need to add new functions and do not need to repeat the existing methods; while interfaces only define methods and constants.
The methods of StringBuilder and StringBuffer will call public methods in AbstractStringBuilder, such as super.append(...). It's just that StringBuffer will add synchronized keyword to the method and synchronize it.
Finally, if the program is not multi-threaded, then using StringBuilder is more efficient than StringBuffer.
The above article in-depth analysis of the differences between String, StringBuffer and StringBuilder in Java is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.