Java Data Type Tutorial - Java StringBuffer.trimToSize()








Syntax

StringBuffer.trimToSize() has the following syntax.

public void trimToSize()

Example

In the following code shows how to use StringBuffer.trimToSize() method.

It trims the unused spaces and checks the length and capacity again.

public class Main {
  public static void main(String[] argv) {
    StringBuffer sb = new StringBuffer();
    sb.append("java2s.com");
    /* w  w w . j a  va2 s. c  o  m*/
    System.out.println(sb.length());
    System.out.println(sb.capacity());
    
    sb.trimToSize();
    
    System.out.println(sb.length());
    System.out.println(sb.capacity());

  }
}

The output: