 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change the length of the StringBuffer Object in Java
The setLength(int newLength) method is used to change the length of the StringBuffer Object. It sets the length of the character sequence. The character sequence is updated to a new one whose length is determined by the value passed as the parameter in the method. The newLength should be greater than or equal to zero.
The java.lang.StringBuffer(int newLength) method is declared as follows −
public void setLength(int newLength)
Let us see a example program illustrating the use of setLength(int newLength) method
Example
public class Example {    public static void main(String[] args) {       StringBuffer sb = new StringBuffer("Hello World");       System.out.println(sb);       System.out.println("Original length : "+sb.length());       System.out.println("Original capacity : "+sb.capacity());       sb.setLength(5); // changing the length of the StringBuffer object       System.out.println();       System.out.println(sb);       System.out.println("New length : " +sb.length());       System.out.println("New capacity : " +sb.capacity());    } }  Output
Hello World Original length : 11 Original capacity : 27 Hello New length : 5 New capacity : 27
Advertisements
 