-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?

Community
  • 1
  • 1
Mithun
  • 7
  • 1

3 Answers3

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.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
claesv
  • 2,075
  • 13
  • 28
  • [Here](http://download.java.net/jdk7/archive/b123/docs/api/java/lang/StringBuilder.html)'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" – Jerome Feb 29 '12 at 07:28
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.

Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
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.

msgmash.com
  • 1,035
  • 5
  • 10