An introduction to the differences between String StringBuffer and StringBuilder in Java

  • 2020-04-01 03:56:22
  • OfStack

In Java, String, StringBuffer, and StringBuilder are String classes that are often used in programming, and the differences between them are often asked in interviews. Now to sum up, look at their differences and similarities.

1. Mutable and immutable

The String class USES an array of characters to hold the String, as shown below, because of the "final" modifier, you know that the String object is immutable.

Private final char value [];

Both StringBuilder and StringBuffer inherit from the AbstractStringBuilder class, and in AbstractStringBuilder you also use a character array to hold strings, as shown below, both objects are mutable.

Char [] value;

2. Is multithreading safe

The object in a String is immutable, which makes it a constant, and obviously thread-safe.

AbstractStringBuilder is the public parent of StringBuilder and StringBuffer and defines some basic operations on strings, such as expandCapacity, append, insert, indexOf, and other public methods.

StringBuffer is thread-safe because it has a synchronization lock on the method or on the method being invoked. See the following source code:


public synchronized StringBuffer reverse() {
    super.reverse();
    return this;
} public int indexOf(String str) {
    return indexOf(str, 0);        //Public synchronized int indexOf(String STR, int fromIndex) method
exists }

StringBuilder does not synchronize methods, so it is not thread-safe.

3.StringBuilder has something in common with StringBuffer

StringBuilder and StringBuffer have a common parent class AbstractStringBuilder(abstract class).

One of the differences between an abstract class and an interface is that public methods can be defined in an abstract class for subclasses that simply add new functionality and do not need to repeatedly write existing methods. Interfaces are just declarations of methods and definitions of constants.

Methods of StringBuilder and StringBuffer both call public methods in AbstractStringBuilder, such as super.append(...) . Only a StringBuffer adds the synchronized keyword to the method to synchronize.

Finally, if the program is not multithreaded, using StringBuilder is more efficient than using StringBuffer.


Related articles: