Java StringBuilder.trimToSize() – Examples

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

trimToSize()

Java StringBuilder.trimToSize() reduces storage used for the character sequence present in the StringBuilder.

The storage reduced to depends on the number of characters present in the sequence of StringBuilder.

ADVERTISEMENT

Syntax

The syntax of trimToSize() function is

trimToSize()

Returns

The function returns nothing.

Example 1 – trimToSize()

In this example, we will initialize a StringBuilder with some string. The length of this string may not equal the capacity of StringBuilder. Usually the capacity is more. But, when you call trimSize() on the StringBuilder object, the capacity of StringBuilder object may be reduced.

Java Program

class Example { 
    public static void main(String[] args) { 
   
        // create a StringBuilder object 
        // with a String passed as parameter 
        StringBuilder stringBuilder = new StringBuilder("abcde"); 
   
        // print capacity 
        System.out.println("Capacity bapplying trimToSize() = "+ stringBuilder.capacity()); 
   
        // applying trimToSize() Method 
        stringBuilder.trimToSize(); 
   
        // print string 
        System.out.println("String = " + stringBuilder.toString()); 
   
        // print capacity 
        System.out.println("Capacity after applying trimToSize() = "+ stringBuilder.capacity()); 
    } 
}

Output

Capacity before applying trimToSize() = 21
String = abcde
Capacity after applying trimToSize() = 5

Example 2 – trimToSize()

In this example, we will take a bigger string, than that of previous example, to initialize the StringBuilder.

Java Program

class Example { 
    public static void main(String[] args) { 
   
        // create a StringBuilder object 
        // with a String passed as parameter 
        StringBuilder stringBuilder = new StringBuilder("abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde"); 
   
        // print capacity 
        System.out.println("Capacity before applying trimToSize() = " + stringBuilder.capacity()); 
   
        // applying trimToSize() Method 
        stringBuilder.trimToSize(); 
   
        // print string 
        System.out.println("String = " + stringBuilder.toString()); 
   
        // print capacity 
        System.out.println("Capacity after applying trimToSize() = "+ stringBuilder.capacity()); 
    } 
}

Output

Capacity before applying trimToSize() = 56
String = abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
Capacity after applying trimToSize() = 40

Conclusion

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