java.lang.StringBuilder trimToSize()
Description
Method Syntax
public void trimToSize()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The trimToSize() method returns void.
Compatibility
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.
package com.javatutorialhq.java.examples; /* * 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 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()); } }
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.