StringBuilder trimToSize() in Java

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

Syntax:

void java.lang.AbstractStringBuilder.trimToSize()

This method 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.

Parameters: NA

Exceptions: NA

Approach

Java

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

        StringBuilder str = 
new StringBuilder("Java is a progamming language.");

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

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


Output:

Capacity = 46 Size = 30 Capacity = 30 Size = 30


No comments:

Post a Comment