Topics Index

Strings > StringBuffer >
Siva Nookala - 20 Feb 2017
The setLength() method of StringBufferclass changes the length of the StringBuffer object to a specified length.
Syntax of setLength method is:
public void setLength(int newLength)

  • The length of the StringBuffer object is reduced to the specified length.
  • The new length can be greater than, equal to or less than the current length.
  • If the specified length is greater than the current length, null characters are padded to attain the specified length. If the specified length is less than the current length then the StringBufferobject is truncated to the required length.
class SetLengthDemo
    public static void main(String arg[])
        StringBuffer sb = new StringBuffer("Java Programming");
        System.out.println(sb + "\nLength = " + sb.length());
        sb.setLength(18); // LINE A
        System.out.println(sb + "\nLength = " + sb.length());
        sb.setCharAt(16, '.');
        sb.setCharAt(17, '.');
        System.out.println(sb + "\nLength = " + sb.length());
        sb.setLength(4); // LINE B
        System.out.println(sb + "\nLength = " + sb.length());    

Java Programming
Length = 16
Java Programming  
Length = 18
Java Programming..
Length = 18
Length = 4


Initially the length was 16 after LINE A the length has been increased to 18. The StringBuffer object padded with null characters is printed. Please note that you can not see the null characters in this output. Then the last two characters are replaced by dot (.) using setCharAt.
At LINE B, the length has been set to 4. The object is truncated to the specified length i.e. the object now contains "Java".

  • Try setting the length to a negative number or zero and see what happens.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.