Differences between String, StringBuffer, and StringBuilder in Java,
Differences between String, StringBuffer, and StringBuilder in Java 1. variable or not
The String class uses character arrays to save strings. Because there is a "final" modifier, the String object is immutable.
/** The value is used for character storage. */ private final char value[];
StringBuffer and StringBuilderAll are inherited from the AbstractStringBuilder class. In AbstractStringBuilder, character arrays are used to save strings, but there is no "final" modifier, so the two objects are variable.
/** * The value is used for character storage. */ char[] value;
2. multi-thread security?
The object in String is immutable, so it can be understood as a constant.Thread-safe.
AbstractStringBuilder is a common parent class of StringBuffer and StringBuilder. It defines some basic string operations, such as append, insert, and indexOf.
StringBuffer adds a Synchronous lock (synchronized) to the method, so it isThread-safe. See the following source code:
1 public synchronized StringBuffer append(String str) {2 toStringCache = null;3 super.append(str);4 return this;5 }
StringBuilder does not apply a synchronization lock to the method, so yesNon-thread-safe. Source code:
1 public StringBuilder append(String str) {2 super.append(str);3 return this;4 }
3. Commonalities Between StringBuffer and StringBuilder
StringBuffer and StringBuilder have common parent classes AbstractStringBuilder (Abstract class).
The StringBuffer and StringBuilder Methods call the public methods in AbstractStringBuilder. The above two source code sections call the super. append (str); only the 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.