StringBuilder vs StringBuffer in Java
Q: What is the difference between a StringBuilder and a StringBuffer in Java? When would you use each one?
- Java
- Senior level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
In Java, both `StringBuilder` and `StringBuffer` are used to represent mutable sequences of characters. However, there are some key differences between the two:
1. Thread-safety: `StringBuffer` is thread-safe, which means that multiple threads can access and modify the same object without any problems. On the other hand, `StringBuilder` is not thread-safe, which means that it should only be used in single-threaded environments.
2. Performance: Because `StringBuffer` is thread-safe, it incurs a performance overhead due to synchronization. In contrast, `StringBuilder` is not thread-safe, so it can provide better performance in single-threaded scenarios.
To summarize, if you need to use a mutable string in a multi-threaded environment, use `StringBuffer`. Otherwise, use `StringBuilder` for better performance in single-threaded scenarios.
Here's an example of how to use `StringBuilder`:
StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(", "); sb.append("world!"); String message = sb.toString(); System.out.println(message); // Output: Hello, world!
And here's an example of how to use `StringBuffer`:
StringBuffer sb = new StringBuffer(); sb.append("Hello"); sb.append(", "); sb.append("world!"); String message = sb.toString(); System.out.println(message); // Output: Hello, world!


