Java StringBuffer trimToSize() Method



The Java StringBuffer trimToSize() method is used to trim the capacity for the character sequence of the StringBuffer 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 StringBuffer 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 StringBuffer class with the value of “Hello World”. Using the trimToSize() method, we are trying to reduce the capacity for the characters sequence of the StringBuffer object.

public class TrimSize {
   public static void main(String[] args) {
      //create an object of the StringBuffer class
      StringBuffer sb = new StringBuffer("Hello World");
      System.out.println("StringBuffer: " + 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 −

StringBuffer: 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 StringBuffer 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.

import java.lang.*;
public class StringBufferDemo {
   public static void main(String[] args) {
      //create an object of the StringBuffer class
      StringBuffer sb = new StringBuffer("Tutorials Point ");
      System.out.println("StringBuffer: " + sb);
      // append the string to StringBuffer
      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 −

StringBuffer: Tutorials Point 
After trim the object: Tutorials Point India
java_lang_stringbuffer.htm
Advertisements