by Dinesh Thakur

void setLength(int newLength) : This method sets (change) the length of the string contained in the StringBuffer object. If the newly specified length is less than the current length of the string buffer, then the string buffer is truncated to contain exactly the number of characters contained in the newlength parameter. If the specified argument is greater than or equal to the current length, sufficient null characters (‘\ u0000') are appended to the string buffer until the total number of characters in the string buffer is equal to the specified length. For example, if following is part of a statement, strl.setLength(10) As a result of this, the string referenced by strl will now contain "Welcome\u0000\u0000\u0000" Similarly, strl. setLength (5) will result in “Hell" .

public class StringsetLength

{
         public static void main(String[] args)
    {
            StringBuffer s3 = new StringBuffer("Hello Java");
            s3.setLength(10);
            System.out.println("s3.capacity () =  " + s3.capacity());
            System.out.println("s3.length() =  "  +  s3.length());
           
     }
}

StringBuffer setLength() in Java Example