String, StringBuffer, and StringBuilder in java are string classes that are often used in programming. The differences between them are also questions that are often asked in interviews. Now let’s summarize and see their differences and similarities.
1. Variable and immutable
The String class uses a character array to save the string, as follows, because there is the "final" modifier, so you can know the string Objects are immutable.
private final char value[]; Both objects are mutable.
Char[] value;
2. Is it multi-thread safe?
The objects in String are immutable, so it can Understood as a constant, it is obviously thread safe.
AbstractStringBuilder is the common parent class of StringBuilder and StringBuffer. It defines some basic string operations, such as expandCapacity, append, insert, indexOf and other public methods.
StringBuffer adds a synchronization lock to the method or adds a synchronization lock to the calling method, so it is thread-safe. Look at the following source code:
public synchronized StringBuffer reverse() { super.reverse(); return this; } public int indexOf(String str) { return indexOf(str, ); //存在 public synchronized int indexOf(String str, int fromIndex) 方法 }StringBuilder does not add synchronization locks to the method, so it is not thread-safe.
3. What StringBuilder and StringBuffer have in common
StringBuilder and StringBuffer have a common parent class, AbstractStringBuilder (abstract class).
One of the differences between abstract classes and interfaces is that abstract classes can define some public methods of subclasses. Subclasses only need to add new functions and do not need to rewrite existing methods; and The interface only contains the declaration of methods and the definition of constants.
The methods of StringBuilder and StringBuffer will call the public methods in AbstractStringBuilder, such as super.append(...). It's just that StringBuffer will add the synchronized keyword to the method for synchronization.
Finally, if the program is not multi-threaded, then using StringBuilder is more efficient than StringBuffer.
* StringBuffer and StringBuilder are both mutable classes, and any changes to strings will not create new objects.
In actual use, 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 efficiency of the program will be slower.
StringBuilder is not thread-safe and is more efficient than StringBuffer in a single thread.
* In summary, the running time of the three:
String > StringBuffer > StringBuilder