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, ); //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.
Summary of the difference between String StringBuffer StringBuilder in Java
* String class is an immutable class. As long as the String is modified, new objects will be generated.
* StringBuffer and StringBuilder are both mutable classes, and no new objects are generated by any changes to strings.
When using it in practice, if you often need to modify a string, such as insertion, deletion, etc.
* But what is the difference between StringBuffer and StringBuilder?
StringBuffer is thread-safe and is very convenient to use in multi-threaded programs, but the program's efficiency will be slower.
StringBuilder is not thread-safe and is more efficient than StringBuffer in a single thread.
* In general, the running time of the three:
String > StringBuffer > StringBuilder