Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between StringBuilder and Stringbuffer? [duplicate]

Tags:

java

Possible Duplicate:
StringBuilder and StringBuffer in Java

what is the difference between StringBuilder and Stringbuffer?

like image 875
billu Avatar asked Jan 22 '23 00:01

billu


2 Answers

Some methods in StringBuffer are synchronized while StringBuilder is not thread-safe - and faster.

Rule of a thumb - use StringBuilder unless you have a use case, where a StringBuilder is used by more then one Thread (which would be a very rare case).

like image 152
Andreas Dolk Avatar answered May 14 '23 09:05

Andreas Dolk


Taken from the javadoc of StringBuffer:

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, {@link StringBuilder}. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

Basically StringBuffer can be used by multiple threads at the same time, since it's synchronized, but that also makes it a bit slower than StringBuilder which can only be used by one thread at a time.

like image 26
Andrei Fierbinteanu Avatar answered May 14 '23 10:05

Andrei Fierbinteanu