capacity() StringBuffer Example

StringBuffer comes with many utility methods to do operations on strings that do not exist in String class. One such method is capacity() StringBuffer.

StringBuffer class comes with two methods – length() to find the number of characters present in the buffer and capacity() method to know the buffer size.

We know StringBuffer comes with an attached buffer to increase the performance. As StringBuffer is mutable, it increases performance over String when the string comes into maximum modifications frequently. To find the current capacity of buffer, use capacity() method.

Infact, StringBuffer stores data in a character array form internally. The capacity is nothing but the initial size of this char array.

As and when the length of string stored in buffer crosss the size of the buffer, the capacity increases automatically to accomodate the extra characters. append() method can be used to add extra characters to the existing.

Following is the method signature of capacity() StringBuffer as defined in Java API.
  • public int capacity(): Returns the existing buffer size (storing capability size) of the StringBuffer object.
Following example uses capacity() StringBuffer method to find the storage capacity.
public class StringBufferMethodDemo
 public static void main(String args[])
   StringBuffer sb1 = new StringBuffer();         // empty buffer
   System.out.println("Buffer size of an empty buffer sb1: " + sb1.capacity()); 

   StringBuffer sb2 = new StringBuffer("Hello");  // buffer with some data initially
   int bufferSize = sb2.capacity();
   System.out.println("Buffer size with Hello initially placed in buffer: " + bufferSize); 

capacity() StringBuffer
Output screenshot of capacity() StringBuffer Example

1. Empty Buffer capacity: The default capacity of the buffer is 16 characters.
2. Capacity with initial data: If initially data like "Hello" is placed in the buffer while creating StringBuffer object itself, the capacity is 16+(number of characters). In the above case, it is 21.
3. Capacity increase: As when the length of the buffer increases over the capacity, another 16 buffer is added implicitly to the existing to accommodate the extra characters appended.
4. Maximum buffer capacity: As the buffer size is in int, the maximum buffer limit is 2^31-1 (that is, Integer.MAX_VALUE-1).

There is a similar method length() in StringBuffer to find the number of characters present in the buffer.

Also know the difference for better understanding: ensureCapacity() vs setLength() vs trimToSize()

Leave a Comment

Your email address will not be published.