On this document we will be showing a java example on how to use the trimToSize() method of StringBuilder Class. Basically the trimToSize() method of StringBuilder 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()

Method Argument

Data Type Parameter Description

Method Returns

The trimToSize() method returns void.


Requires Java 1.5 and up

Java StringBuilder trimToSize() Example

Below is a java code demonstrates the use of trimToSize() method of StringBuilder class. The example presented might be simple however it shows the behavior of the trimToSize() method.


 * A java example source code to demonstrate
 * the use of trimToSize() method of StringBuilder class

public class StringBuilderTrimToSizeExample {

	public static void main(String[] args) {

		// initialize the StringBuilder object
		StringBuilder sb = new StringBuilder("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
		System.out.println("Length after trimming:" + sb.length());
		System.out.println("Capacity after trimming:" + sb.capacity());
		System.out.println("Contents after trimming:" + sb.toString());

The java example source code above, demonstrates the use of trimToSize() method of StringBuilder class. Initially wecode assign a string “java tutorial” as initial contents of the StringBuilder. The length of the string is 13 as can be found using length() method. 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.

Sample Output

Below is the sample output when you run the above example.

StringBuilder trimToSize() example output