VOOZH about

URL: https://www.geeksforgeeks.org/java/java-stringbuffer-capacity-method/

⇱ Java StringBuffer capacity() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java StringBuffer capacity() Method

Last Updated : 23 Jul, 2025

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.


Output
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.

Syntax of capacity() Method

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.


Output
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,

  • When 16 is exceeded, the capacity is expected to become (16 * 2) + 2 = 34.
  • Since the appended content requires more space, Java adjusts the capacity to 47 by ensuring enough space for the additional text.

Example 3: The below Java program demonstrates a null reference cause a NullPointerException, if we try to call the capacity() method on it.

Output:

👁 Output

Note: A Stringbuffer can be initialized as null, but attempting to call a method on it will cause a NullPointerException.

Comment
Article Tags: