Home » Java programming language

Java StringBuffer void trimToSize() method with Example

Java StringBuffer void trimToSize() method: Here, we are going to learn about the void trimToSize() method of StringBuffer class with its syntax and example.
Submitted by Preeti Jain, on June 30, 2019

StringBuffer Class void trimToSize()

  • This method is available in package java.lang.StringBuffer.trimToSize().
  • This method is used to reduce or save memory space available for the StringBuffer object or in other words, we can say it is used to trim the size of the given object.
  • If memory space is larger than the holding object, in that case, we need to reduce space for future purpose.

Syntax:

    void trimToSize(){
    }

Parameter(s):

We don't pass any object in the method of the StringBuffer.

Return value:

The return type of this method is void that means this method returns nothing.

Java program to demonstrate example of trimToSize() method

import java.lang.StringBuffer;

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

        StringBuffer sb = new StringBuffer(" StringBuffer class is ");

        // use append(String s) append the string to the StringBuffer object
        sb.append("java.lang");
        sb.trimToSize();

        // Display result after implementing trimToSize()

        System.out.println("The result will be after implementing method trimToSize() is :" + sb);

        sb = new StringBuffer("Current version of java is :");

        // use append(String s) append the string to the StringBuffer object
        sb.append("8");
        sb.trimToSize();

        // Display result after implementing trimToSize()

        System.out.println("The result will be after implementing method trimToSize() is :" + sb);
    }
}

Output

D:\Programs>javac StringBufferClass.java

D:\Programs>java StringBufferClass
The result will be after implementing method trimToSize() is : StringBuffer class is java.lang
The result will be after implementing method trimToSize() is :Current version of java is :8



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.