Explain the differences between String StringBuilder and StringBuffer in java in detail
- 2021-08-28 20:12:42
- OfStack
Do you know the difference between String, StringBuilder and Stringbuffer? When you create strings, have you considered which one to use?
Don't worry, this article will take you to solve these problems.
Variability
First of all, String is a string, and we declare it as follows:
String s = "abc";
The String class uses an char array modified by final to store the contents of a string. Its 1 major feature is immutability. How do you understand this immutability?
As we know, if a class is decorated with final, the class cannot be inherited, the methods cannot be overridden, and the properties cannot be changed.
Look at this code:
String s = "abc";
s = s+1;
System.out.print(s); // Output : abc1
On the surface, the value of s has changed from abc to abc1, but this is not the case. Instead, when the +1 operation is performed, a new String object is recreated and assigned as abc1.
Both StringBuilder and StringBuffer use char arrays to store strings, but they are not decorated with final, so the content they create is variable and does not create a new object like String.
Thread safety
String is a constant, so there is no thread insecurity, but StringBuilder and StringBuffer are variables, so we need to consider this.
Let's look at the source code for StringBuilder:
@Override
public int compareTo(StringBuilder another) {
return super.compareTo(another);
}
@Override
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
}
Look at StringBuffer again:
@Override
public synchronized int compareTo(StringBuffer another) {
return super.compareTo(another);
}
@Override
public synchronized int length() {
return count;
}
@Override
public synchronized int capacity() {
return super.capacity();
}
No, synchronized synchronization locks are added to each method of StringBuffer to ensure thread safety, while StringBuilder does not.
Performance comparison
StringBuilder > StringBuffer > String
As a constant, String creates a new object every time it is changed, and the performance is the lowest; The StringBuilder does not have the locks on the StringBuffer, so it performs better.