Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the capacity of a StringBuffer?

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?

like image 913
Иван Бишевац Avatar asked Nov 04 '11 15:11

Иван Бишевац


People also ask

How do you find the capacity of a StringBuffer?

Calculating the StringBuffer capacity The capacity of the StringBuffer denotes the number of characters in the StringBuffer. StringBuffer sb = new StringBuffer(225); While appending data to the StringBuffer object, once you exceed the initial capacity the capacity of the StringBuffer object is increased.

What is capacity in StringBuilder?

The default capacity of StringBuilder class is 16 bytes. Syntax: int capacity(): This method returns the capacity of the StringBuilder object. The default capacity of the StringBuilder is 16 bytes.

What is the difference between length and capacity of StringBuffer?

A string buffer or string builder's length is the number of characters it contains; its capacity is the number of character spaces that have been allocated.

What is the use of capacity in Java?

The capacity() method of the StringBuffer class in Java is used to return buffer capacity. By default, a string buffer has a 16 character capacity. By calling this method, we can calculate its current capacity. Capacity refers to the total number of character storage size in a string buffer.


2 Answers

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

like image 59
Ulf Jaehrig Avatar answered Nov 08 '22 11:11

Ulf Jaehrig


It's the size of internal buffer. As Javadoc says:

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

like image 3
Andrey Adamovich Avatar answered Nov 08 '22 12:11

Andrey Adamovich