Java StringBuilder capacity() Method Example

Java StringBuilder capacity() method returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which allocation will occur.

Java StringBuilder capacity() Method Example

This simple program demonstrates the usage of capacity() method.
public class CapacityExample {
    public static void main(String[] args) {
        StringBuilderbuilder = new StringBuilder("javaguides");
        int capacity = builder.capacity();
  
        // inital capacity
        System.out.println(new StringBuilder().capacity());
  
        // intial capacity 16 + number of characters in string
        System.out.println("Capacity of the string :: " + capacity);
    }
}
Output:
16
Capacity of the string :: 26

Reference



Comments