What is String Builder and String Buffer?
Both String Builder and String Buffer are mutable. That mean use can change the value of String object
The difference between String Buffer and String Builder is String Builder using asynchronous mechanisms, so it has a faster speed but not safe for multiple thread.
On the other hand, String Buffer using synchronous mechanism, so it has slower speed compared to Spring Builder, but it is thread safe
Example :
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(“Hello”);
sb.append(” World”);
sb.append(“!”);
System.out.println(sb.toString()); // Output: Hello World!
}
}
StringBuilder
is not thread-safe but provides faster performance in single-threaded environments.
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(“Hello”);
sb.append(” World”);
sb.append(“!”);
System.out.println(sb.toString()); // Output: Hello World!
}
}
StringBuffer
is thread-safe and can be safely used in a multi-threaded environment but with a performance cost.