In Java, String, StringBuffer, and StringBuilder are often used as string classes in programming, and the difference between them is often the question they ask in an interview. Now to summarize, look at their differences and the same.
1. Variable and not variable
The string class uses a character array to hold the strings, as follows, because there is a "final" modifier, so you know that the string object is immutable.
Private final char value[];
Both StringBuilder and StringBuffer inherit from the Abstractstringbuilder class, and in Abstractstringbuilder the string is also saved using a character array, as follows: Both objects are mutable.
Char[] value;
2. Whether multithreading security
Objects in string are immutable and can be understood as constants, apparently thread-safe .
Abstractstringbuilder is the common parent class of StringBuilder and StringBuffer, which defines the basic operations of strings, such as expandcapacity, append, inserts, IndexOf, and other public methods.
StringBuffer is thread-safe by adding a synchronous lock to a method or by synchronizing the method that is invoked. Look at the following source code:
Copy Code code as follows:
Public synchronized StringBuffer reverse () {
Super.reverse ();
return this;
}
public int indexOf (String str) {
return indexOf (str, 0); There is a public synchronized int indexOf (String str, int fromindex) method
}
StringBuilder does not have a synchronized lock on the method, so it is not thread-safe .
3.StringBuilder and StringBuffer in common
StringBuilder and StringBuffer have a common parent class Abstractstringbuilder (abstract Class).
One of the differences between an abstract class and an interface is that a common method of subclasses can be defined in an abstract class, and subclasses simply need to add new functionality and do not have to repeat the existing methods, while the interface simply defines the method's declarations and constants.
StringBuilder, StringBuffer methods call public methods in Abstractstringbuilder, such as Super.append (...). Just stringbuffer will add synchronized keyword on the method and synchronize.
Finally, if the program is not multithreaded, then using StringBuilder is more efficient than stringbuffer.