![]() |
VOOZH | about |
In Java, the capacity() method is used in the StringBuilder and StringBuffer classes to retrieve the current capacity of the object. The capacity is the amount of space that has been allocated to store the string that can grow dynamically as needed.
Example 1: The below Java program demonstrates the use of the capacity() method to check the initial capacity of a StringBuffer object.
Default Capacity: 16
Note: By default, the initial capacity of a StringBuffer is 16 characters and it is same for the StringBuilder class as well.
public int capacity()
Return Type: The method returns an int that represents the current capacity of the StringBuilder or StringBuffer object.
Example 2: The below Java program demonstrates how the capacity of a StringBuffer changes when text is added to exceed its current capacity.
Default capacity: 16 Capacity after adding some text: 16 Capacity after adding more text: 47
Explanation: In the above example, initially, the default capacity is 16. Then we have added text within the initial capacity which does not increase the capacity. When the text exceeds the current capacity, the new capacity is generally calculated as (old capacity * 2) + 2. For example,
Example 3: The below Java program demonstrates a null reference cause a NullPointerException, if we try to call the capacity() method on it.
Output:
Note: A Stringbuffer can be initialized as null, but attempting to call a method on it will cause a NullPointerException.