Menu
Topics Index
...
`

StringBuffersetLength - Java Example Program


StringBuffersetLength
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());    
    }
}
OUTPUT

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

DESCRIPTION

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".

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

© meritcampus 2019

All Rights Reserved.

Open In App