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?
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With