-1

Possible Duplicate:
StringBuilder and StringBuffer in Java

I would like to know the difference between the StringBuilder and StringBuffer. In StringBuffer it automatically allocates 16 character. When we add a string "hello" its capacity is increased to 21. Could any one clarify my doubts?

1
  • 1
    -1 for not reading the Javadoc first. Commented Feb 29, 2012 at 9:25

3 Answers 3

6

Have you looked at the Javadocs?

From http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html:

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). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Sign up to request clarification or add additional context in comments.

1 Comment

Here's the JDK 7 javadoc: "Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used"
3

The main difference is , StringBuffer is thread safe (all of its methods are synchronized),but StringBuilder is not. But StringBuilder is faster than the StringBuffer.Use StringBuilder if you don't need thread-safety.

Comments

2

StringBuffer is thread-safe (i.e, its methods are synchronised). However, this isn't needed by every application and it makes the code slower than it would otherwise be. StringBuilder is essentially StringBuffer without the synchronization, and hence a bit faster.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.