java.lang.StringBuffer trimToSize()

Description :

This java tutorial shows how to use the trimToSize() method of StringBuffer class under java.lang package.

The trimToSize() method of StringBuffer class attempts to reduce storage used for the character sequence. If the buffer is larger than necessary to hold its current sequence of characters, then it may be resized to become more space efficient. Calling this method may, but is not required to, affect the value returned by a subsequent call to the capacity() method.

Method Syntax :

public void trimToSize()

Parameter Input :

DataType Parameter Description
N/A N/A N/A

Compatibility Version :

Requires Java 1.5 and up

Java Code Example :

This java example source code demonstrates the use of trimToSize() method of StringBuffer class. Initially the code assigns a string “java tutorial” as initial contents of the string buffer. The length of the string is 13. With the initial capacity of the buffer to be 16, the capacity is now 29.  However we called the trimToSize() method to reduce the capacity of the buffer. Due to that, the capacity becomes the length of the string inside the buffer.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of trimToSize()
 * of StringBuffer class
 */

public class StringBufferTrimToSize {

	public static void main(String[] args) {		
		
        // initialize the StringBuffer object
        StringBuffer sb = new StringBuffer("java tutorial");
        System.out.println("Length of buffer:"+sb.length());        
        System.out.println("Capacity:"+sb.capacity());  
        System.out.println("Contents of buffer:"+sb);
       
        // try to reduce the size of the buffer
        sb.trimToSize();
        System.out.println("Length after trimming:"+sb.length());
        System.out.println("Capacity after trimming:"+sb.capacity());
        System.out.println("Contents after trimming:"+sb.toString());
        
	}
}

Sample Output :

Running the trimToSize() method example source code of StringBuffer class will give you the following output

Length of buffer:13
Capacity:29
Contents of buffer:java tutorial
Length after trimming:13
Capacity after trimming:13
Contents after trimming:java tutorial

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :