What is the difference between StringBuffer and StringBuilder in Java?

What is the difference between StringBuffer and StringBuilder in Java?

Ninja Asked on 17th September 2018 in Java.
Add Comment
1 Answer(s)
Best answer

StringBuffer is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. String buffers are safe for use by multiple threads since the methods are synchronized.

StringBuilder is also a mutable sequence of characters introduced in Java 5, but not synchronized. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). It is recommended that StringBuilder be used in preference to StringBuffer as it will be faster under most implementations.

Note: Never manipulate Strings inside loops, as it would create as many objects as the loop goes on.

Ninja Answered on 17th September 2018.
Add Comment