trimToSize() StringBuffer Example

When the coding comes to an end with string manipulation in the buffer and further no modification is required, keeping extra buffer is memory waste. To remove the extra buffer than required to hold the characters, Programmer calls this method.

What Java API says:

  • public synchronized void trimToSize(): Deletes the extra buffer existing more than the length. Introduced with JDK 1.5 version.

Following example illustrates the method with 4 StringBuffer objects.

public class Demo
  public static void main(String args[])
    StringBuffer sb1 = new StringBuffer("ABC");
    System.out.println("String length in the buffer before trimToSize(): " + sb1.length());  // 6
    System.out.println("Buffer capacity before trimToSize(): " + sb1.capacity());            // 19

    System.out.println("\nString length in the buffer after trimToSize(): " + sb1.length()); // 6
    System.out.println("Buffer capacity after trimToSize(): " + sb1.capacity());             // 6

trimToSize() StringBuffer Example
Output screenshot on trimToSize() StringBuffer Example

Observe, after trimToSize() is called, the buffer is reduced from 19 to 6, just sufficient to store 6 characters.

For better understanding, know the difference: ensureCapacity() vs setLength() vs trimToSize().

Pass your comments and suggestions on this tutorial "trimToSize() StringBuffer Example".

Leave a Comment

Your email address will not be published.