StringBuffer and StringBuilder are very important concepts in Java to play with String. But do you know when to use which? Let’s understand it.
StringBuffer came first. Sun Microsystems (Company behind Java) was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.
StringBuilder came later. Most of the uses of StringBuffer were single-thread and unnecessarily paying the cost of the synchronization.
Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, within the same location.
StringBuffer is synchronized whereas StringBuilder is not synchronized by default.
Meaning of synchronization
When something is synchronized, then multiple threads can access, and modify it without any problem or side effect.
When to use which
When you need a string, which can be modifiable, and only one thread is accessing and modifying it, use StringBuilder.
When you need a string, which can be modifiable, and multiple threads are accessing and modifying it, use StringBuffer.
Conclusion
StringBuilder is more efficient as it’s unsynchronized (meaning less overhead). Simply use StringBuilder unless you really are trying to share a buffer between threads.