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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.