Java - StringBuilder trimToSize() Method



The Java StringBuilder trimToSize() method is used to trim the capacity for the character sequence of the StringBuilder object. In short, it attempts to reduce the storage used for the character sequence.

In Java, a trim() is an inbuilt method that is generally used to remove or trim the white-spaces of the given sequence or string.

The trimToSize() does not accept any parameter, the method does not throw any exception. It is not returning any value.

Syntax

Following is the syntax of the Java StringBuilder trimToSize() method −

public void trimToSize()

Parameters

  • It does not accept any parameter.

Return Value

This method does not return any value.

Example

If the value of the StringBuffer object is not null, the trimToSize() method reduces the capacity of the given sequence.

In the following example, we are instantiating the StringBuilder class with the value of “Hello World”. Using the trimToSize() method, we are trying to reduce the capacity for the characters sequence of the StringBuilder object.

package com.tutorialspoint.StringBuilder;
public class TrimSize {
   public static void main(String[] args) {
      
      //create an object of the StringBuilder class
      StringBuilder sb = new StringBuilder("Hello World");
      System.out.println("StringBuilder: " + sb);
      
      //get the capacity and length
      System.out.println("The length of the sequence: " + sb.length());
      System.out.println("The sequence capacity before trim: " + sb.capacity());
      
      //using the trimToSize() method
      sb.trimToSize();
      System.out.println("The sequence capacity after trim: " + sb.capacity());
   }
}

Output

On executing the above program, it will produce the following result −

StringBuilder: Hello World
The length of the sequence: 11
The sequence capacity before trim: 27
The sequence capacity after trim: 11

Example

In the following example, we are creating an object of the StringBuilder class with the value of “Tutorials Point”. Then, using the append() method we are appending the “India” value to it. Using the trimToSize() method, we are trying to reduce its capacity.

package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
   public static void main(String[] args) {
      
      //create an object of the StringBuilder class
      StringBuilder sb = new StringBuilder("Tutorials Point ");
      System.out.println("StringBuilder: " + sb);
      
      // append the string to StringBuilder
      sb.append("India");
      
      //By using trimToSize() method is to trim the sb object
      sb.trimToSize();
      System.out.println("After trim the object: " + sb);
   }
}

Output

Following is the output of the above program −

StringBuilder: Tutorials Point 
After trim the object: Tutorials Point India
java_lang_stringbuilder.htm
Advertisements