Home » Java programming language

Java StringBuffer void setLength(int newlen) method with Example

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

StringBuffer Class void setLength(int newlen)

  • This method is available in package java.lang.StringBuffer.setLength(int newlen).
  • This method is used to sets the length of the new StringBuffer or in other words we can resize the StringBuffer if we want.
  • This method will raise an exception if the new buffer length is greater than or equal to the length of the current StringBuffer object.

Syntax:

    void setLength(int newlen){
    }

Parameter(s):

We pass only one object in the method of the StringBuffer i.e. newlength(newlen).

Return value:

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

Java program to demonstrate example of setLength() method

import java.lang.StringBuffer;

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

        StringBuffer sb = new StringBuffer(" java.lang is a package ");

        // Display Current StringBuffer object sb 
        System.out.println("The current StringBuffer is : " + sb);
        // Display Current length of the StringBuffer object sb
        System.out.println("The current length of StringBuffer object is : " + sb.length());

        // Implement setLength(int newlen) update the new length of the StringBuffer
        sb.setLength(9);
        System.out.println("The updated length of the StringBuffer object is : " + sb.length());

        // Display Updated StringBuffer object sb
        System.out.println("The updated StringBuffer object is :" + sb);
    }
}

Output

D:\Programs>javac StringBufferClass.java

D:\Programs>java StringBufferClass
The current StringBuffer is : java.lang is a package
The current length of StringBuffer object is : 23
The updated length of the StringBuffer object is : 9
The updated StringBuffer object is :java.lang


Comments and Discussions!

Load comments ↻





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