Java StringBuilder.capacity() – Examples

In this tutorial, we will learn about the Java StringBuilder.capacity() function, and learn how to use this function to find the current capacity of StringBuilder, with the help of examples.

capacity()

StringBuilder.capacity() returns the current capacity of this StringBuilder object.

ADVERTISEMENT

Syntax

The syntax of capacity() function is

capacity()

Returns

The function returns int

Example 1 – capacity()

In this example, we will create an empty StringBuilder. We will print the default initial capacity of this StringBuilder object. Then we will add a string of length, say 25, and find the current capacity of this StringBuilder. We shall use capacity() method to find the current capacity of StringBuilder.

Java Program

public class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object, 
        // default capacity will be 16 
        StringBuilder stringBuilder = new StringBuilder(); 
        // get default capacity 
        int capacity = stringBuilder.capacity(); 
        System.out.println("Initial Capacity of StringBuilder : "+ capacity); 

        // add the String to StringBuilder Object 
        stringBuilder.append("abcdeabcdeabcdeabcdeabcde"); 
        // get capacity 
        capacity = stringBuilder.capacity();  
        System.out.println("Current Capacity of StringBuilder : " + capacity);  
    } 
}

Output

Initial Capacity of StringBuilder : 16
Current Capacity of StringBuilder : 34

Example 2 – capacity()

In this example, we will create a StringBuilder object with a string literal. We will print the initial capacity of this StringBuilder object. Then we will add a string of length, say 30, and find the current capacity of this StringBuilder.

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder("abcdeabcdeabcdeabcde"); 
        // get initial capacity 
        int capacity = stringBuilder.capacity(); 
        System.out.println("Initial Capacity of StringBuilder : "+ capacity); 

        // add the String to StringBuilder Object 
        stringBuilder.append("fghijfghijfghijfghijfghijfghij"); 
        // get current capacity 
        capacity = stringBuilder.capacity();  
        System.out.println("Current Capacity of StringBuilder : " + capacity);  
    } 
}

Output

Initial Capacity of StringBuilder : 36
Current Capacity of StringBuilder : 74

Conclusion

In this Java Tutorial, we have learnt the syntax of Java StringBuilder.capacity() function, and also learnt how to use this function with the help of examples.