Similarities and differences between String, StringBuffer, and StringBuilder
The biggest difference between String, StringBuffer, and StringBuilder is that String is an immutable object, while StringBuffer and StringBuilder are mutable objects. Immutable means [immutable mechanism and benefits] The value stored in the object remains unchanged. The next problem is: "if the object is immutable, How can I change the object content when I want to change it?" Accurately speaking, the changed String object is not the same as the String object before the change.
Assume that you declare the following String object:
String myString = hello;
Next, how do you add "Guest" to the same String object?
myString = myString + ” Guest”;
When you print the content of myString, the output is "Hello Guest ". although we use the same object (mySting), a new object is created internally. Therefore, if we perform similar operations on the String, for example, if you modify a String object such as append and trim, you actually create a new String object.
The question is, will this cause performance problems? The answer is yes. So how to make the String operation more efficient is by using StringBuffer and StringBuilder.
Because the StringBuffer and StringBuilder objects are variable, we can change some values stored in objects. Effective means that StringBuffer and StringBuilder are more effective in some operations such as append than String.
So what is the difference between StringBuffer and StringBuilder?
StringBuffer and StringBuilder have the same method, but StringBuffer is synchronized while StringBuilder is not synchronized, so if you don't want to use a thread, using StringBuilder will be more effective (because this reduces the cost of synchronization ).
How to Use StringBuilder:
First, let's look at the String method:
String s = “Hello”;s = s + ” World”;system.out.println(s);
Let's take a look at the StringBuilder method:
StringBuilder sb = new StringBuilder(“Hello”);sb.append(” World”);system.out.println(sb);
Run another example below to show that the String object is immutable. Let's take a look at the following code:
Package com. other. test; public class StringTest {public static void main (String [] args) {String s = for a test; s. concat (if it is the same object, this sentence should be output !); System. out. println (s); s = s. concat (if only this sentence is output, it proves that String is immutable); System. out. println (s );}}
The output result is:
To a test
If only this sentence is output, it proves that the String is immutable.
The code above proves that the String is immutable, so the result of a concat operation is that the value is stored in the new object.
In addition, StringBuilder is introduced in java1.5 (if you are a previous version, you can only use StringBuffer ).