String, StringBuffer, and StringBuilder in Java are string classes often used in programming. The difference between them is also a problem that often asks in interviews. To sum up, look at their differences and the same.
1. Variable and unchanged
The String class uses the character array to save the string. As follows, because there is a "final" modifier, you can know that the String object is immutable.
Private Final Char value [];
Both StringBuilder and StringBuffer are inherited from the ABSTRACTSTRINGBUILDER class. In ABSTRACTSTRINGBUILEDER, the character array is also used to save the character string. As we know, these two objects are variable.
char [] value;
2. Is it safe?
Objects in String are immutable, which can be understood as constant, obviously thread is safe.
AbstractstringBuilder is a public parent class between StringBuilder and StringBuffer, defining basic operants of some string, such as ExpandCapAcity, APPEND, Insert, Indexof and other public methods.
StringBuffer adds a synchronous lock or the call method is added to the method, so it is thread -safe. See 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); // Public synchronized int indexof (String Str, Int FROMINDEX) method
}
StringBuilder does not have a synchronous lock on the method, so it is non -threaded security.
3. StringBuilder and StringBuffer in common
StringBuilder and StringBuffer have public parent -class ABSTRACTSTRINGBUILDER (abstract class).
One of the differences between abstract classes and interfaces is: some public methods of some subclasses can be defined in abstract classes. Subclass only needs to add new functions, and no need to repeatedly write existing methods; while the interface is only the statement and constant of the method in the interface. Definition.
The methods of StringBuilder and StringBuffer all call public methods in ABSTRACTSTRINGBUILDER, such as super.appending (...). It's just that StringBuffer will add the synchronized keyword to the method to synchronize.
Finally, if the program is not multi -threaded, the efficiency of using StringBuilder is higher than StringBuffer.