What is the capacity of a StringBuffer?

Иван Бишевац picture Иван Бишевац · Nov 4, 2011 · Viewed 23.7k times · Source

When I run this code:

StringBuffer name = new StringBuffer("stackoverflow.com");
System.out.println("Length: " + name.length() + ", capacity: " + name.capacity());

it gives output:

Length: 17, capacity: 33

Obvious length is related to number of characters in string, but I am not sure what capacity is? Is that number of characters that StringBuffer can hold before reallocating space?

Answer

Ulf Jaehrig picture Ulf Jaehrig · Nov 4, 2011

See: JavaSE 6 java.lang.StringBuffer capacity()

But your assumption is correct:

The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur