setLength() StringBuffer Example

setLength() StringBuffer Example


setLength() StringBuffer method sets the number of characters that can exist in the buffer. Must be careful in the usage: if the setLengtgh() is set with less size of number of characters, the extra characters in the buffer will be truncated off.

What Java API says ablout setLength() StringBuffer:

public synchronized void setLength(int newLength): sets the capacity for the new length of characters. If the new length specified in the method is greater than the current length, null characters (‘\u0000’) are appended so that the current length becomes new length (null characters are not printed in output, see example). If the newLength is less than the current length, the current length is truncated to the newLength loosing data. If the argument is negative, StringIndexOutOfBoundsException is thrown. See the example.

Following setLength() StringBuffer example illustrates the method with 4 StringBuffer objects.


setLength() StringBuffer Example
Output screen of setLength() StringBuffer Example

Observe, setLength() method does not modify the buffer capacity, but modifies the length. length denotes the number of characters present in the buffer.

Leave a Reply

Your email address will not be published. Required fields are marked *