trimToSize() StringBuffer Example

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.


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 Reply

Your email address will not be published. Required fields are marked *