StringBuffer trimToSize() in Java

trimToSize(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

void java.lang.StringBuffer.trimToSize()

This method attempts to reduce the 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.

Approach

Java

public class TrimToSize {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        System.out.println("Capacity = " + 
str.capacity() + " Length = " + str.length());
        str.trimToSize();

        System.out.println("Capacity = " + 
str.capacity() + " Length = " + str.length());
    }
}


Output:

Capacity = 27 Length = 11 Capacity = 11 Length = 11


No comments:

Post a Comment