Thursday, 10 July 2014

setLength (int newLength)

public void setLength(int newLength)
Sets the length of the character sequence. If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended so that length becomes the newLength argument. if the newLength argument is less than the current length, the length is changed to the specified length and extra characters are removed.

public class StringBufferSetLength {
    public static void main(String args[]){
        StringBuffer s1 = new StringBuffer("Hello, how are you");
        StringBuffer s2 = new StringBuffer("Hello, how are you");
        
        System.out.println("s1 = "+s1);
        System.out.println("s2 = "+s2);
        
        s1.setLength(10);
        s2.setLength(30);
        
        System.out.println("s1 = "+s1);
        System.out.println("s2 = "+s2);
        
        System.out.println("Length of s1 is " + s1.length());
        System.out.println("Length of s2 is " + s2.length());
    }
}

Output
s1 = Hello, how are you
s2 = Hello, how are you
s1 = Hello, how
s2 = Hello, how are you
Length of s1 is 10
Length of s2 is 30

1. Throws IndexOutOfBoundsException, if the newLength argument is negative.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment