Strings are string constants (which cannot be changed after creation), StringBuilder and StringBuffer objects are string variables (which can be changed), and the main differences are in execution speed and thread safety.
Execution speed
Execution speed: StringBuilder > StringBuffer > String
Reason:
The change to a string object constantly creates and reclaims a string object, while StringBuilder, StringBuffer does not.
For example:
String str = "123"; = str + "456"; System.out.println (str);
The JVM is the process of handling these four lines of code:
1. Create a String object and assign a value of "123".
2. Print the string.
3. Create a new string object, assign the value of the 1th object to it after "456", and the GC (garbage collection mechanism) to reclaim the first object.
4. Print a new string.
Thread Safety
StringBuilder: Non-thread-safe.
StringBuffer: Thread-Safe (synchronous mechanism assurance).
Usage Scenarios
String: A small number of string operations.
StringBuilder: Single thread large number of string operations.
StringBuffer: Multithreading a large number of string operations.
Java String, StringBuilder, stringbuffer[notes]