Differences between String, StringBuffer, and StringBuilder in java
In java, String, StringBuffer, and StringBuilder are String classes that are frequently used in programming. The differences between them are also frequently asked during interviews. Now, let's take a look at their differences and similarities. 1. Use character arrays in variable and immutable String classes to save strings. The following figure shows that the string object is immutable because of the "final" modifier. Private final char value []; both StringBuilder and StringBuffer inherit from the AbstractStringBuilder class. In AbstractStringBuilder, character arrays are also used to save strings. The following is an example. We can see that both objects are variable. Char [] value; 2. whether the object in the multi-thread security String is immutable. It can be understood as a constant, obviously thread security. AbstractStringBuilder is a 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 Synchronous lock to the method or a Synchronous lock to the called method, so it is thread-safe. See the following source code: Copy code 1 public synchronized StringBuffer reverse () {2 super. reverse (); 3 return this; 4} 5 6 public int indexOf (String str) {7 return indexOf (str, 0); // public synchronized int indexOf (String str, int fromIndex) Method 8} The replication code StringBuilder does not apply a synchronization lock to the method, so it is non-thread-safe. 3. What StringBuilder and StringBuffer have in common is that StringBuilder and StringBuffer have a common parent class AbstractStringBuilder (abstract class ). One difference between an abstract class and an interface is that an abstract class can define public methods for some subclasses. To do this, you only need to add new functions and do not need to repeat existing methods; the interface only defines the Declaration and constant of the method. The StringBuilder and StringBuffer Methods call the public methods in AbstractStringBuilder, such as super. append (...). Only StringBuffer will add the synchronized keyword to the method for synchronization. Finally, if the program is not multi-threaded, StringBuilder is more efficient than StringBuffer.