Differences in string, StringBuffer, StringBuilder in Java 1. From a variable angle
The string class uses character arrays to hold strings because there is a "final" modifier, so the string object is immutable.
/***/ privatefinalchar value[];
Both StringBuffer and StringBuilder inherit from the Abstractstringbuilder class, and in Abstractstringbuilder they also use character arrays to hold strings, but no "final" modifier, so both objects are mutable.
/** * The value is used for character storage. */ Char [] value;
2. Whether multithreaded security
The objects in string are immutable and can be understood as constants, so they are thread-safe .
Abstractstringbuilder is the public parent of StringBuffer and StringBuilder, and defines some basic operations for strings, such as append, insert, indexof, and other public methods.
StringBuffer adds a synchronous lock (synchronized) to the method, so it is thread-safe . See the following source code:
1 Public synchronized stringbuffer Append (String str) {2 NULL ; 3 Super . Append (str); 4 return This ; 5 }
StringBuilder does not have a synchronous lock on the method, so it is non-thread safe . The following source code:
1 Public StringBuilder Append (String str) {2 Super . Append (str); 3 return This ; 4 }
What 3.StringBuffer and StringBuilder have in common
StringBuffer and StringBuilder have public parent class Abstractstringbuilder ( abstract class ).
The methods of StringBuffer and StringBuilder call the public methods in Abstractstringbuilder, such as Super.append (str) is called in the above two-segment source code; Just stringbuffer will add synchronized keywords to the method and synchronize.
Finally, if the program is not multithreaded, then using StringBuilder is more efficient than stringbuffer.
The difference between string, StringBuffer, StringBuilder in Java