I have made following code.The first statement gives me output 21.
That is i know that default capacity is 16 + 5 for Hello

But i don't get, why it gives 44 as output as i am increasing capacity from 21 to 30 by using ensurecapacity() method.

StringBuffer sb  = new StringBuffer("hello");
System.out.println(sb.capacity());//output 21
System.out.println(sb.capacity());//output 44

is it the thing that we have to use ensurecapacity() method only when we have created instance of this class with constructor

StringBuffer sb  = new StringBuffer(5);

can anyone give me proper justification on it?

4 Years
Discussion Span
Last Post by jalpesh_007

how else would you create a StringBuffer instance?
and yes, since ensureCapacity is not a static method, you'll need to have an instance of StringBuffer to call it on.


The capacity 44 is two plus twice the old capacity of 21. In other words sb.capacity() = 44 = 2 * 21 + 2. That's what the documentation for ensureCapacity says it should be.

I hope everyone is aware that StringBuilder is superior to StringBuffer.


I hope everyone is aware that StringBuilder is superior to StringBuffer.

For those who aren't, the reason is that StringBuffer synchronizes on every call, while StringBuilder doesn't, therefore StringBuffer is thread-safe, and StringBuilder isn't.
Truth is that most of the time you don't need the thread-safety offered by StringBuffer, so it makes sense to use StringBuilder.
As an extra benefit StringBuilder will likely be faster than StringBuilder due to the lack of synchronizing.

Here's how it is stated in the Java API:

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.
(StringBuilder - Java API)

Personally I think that the real-world use cases of a StringBuffer are pretty limited. Imagine two threads operating on a single shared StringBuffer.
Threads can switch back and forth and there are no guarantees about the order in which the threads will access the shared StringBuffer.

Edited by mvmalderen

Votes + Comments
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.