java.lang.StringBuffer trimToSize()

Description :

This java tutorial shows how to use the trimToSize() method of StringBuffer class under java.lang package.

The trimToSize() method of StringBuffer 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()

Parameter Input :

DataType Parameter Description
N/A N/A N/A

Compatibility Version :

Requires Java 1.5 and up

Java Code Example :

This java example source code demonstrates the use of trimToSize() method of StringBuffer class. Initially the code assigns a string “java tutorial” as initial contents of the string buffer. The length of the string is 13. 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 :

Running the trimToSize() method example source code of StringBuffer class will give you the following output

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :