Java StringBuilder setLength() methodThe setLength(int newLength) method of StringBuilder class is used to set the new length of the character sequence. The new length of character sequence becomes to specified newLength argument. If the newLength argument is less than the current length, the new length of character sequence will change to newLength. On the other hand, if the newLength argument is greater than the current length then the null character(s) '\u0000' are appended so that length becomes the newLength argument. Syntax:Parameter:
Returns:NA Exception:IndexOutOfBoundsException - if the newLength argument is negative. Compatibility Version:Java 1.5 and above Example 1Test it NowOutput: string: stringbuilder length: 13 set new length: 6 new sequence: string Example 2Test it NowOutput: string: stringbuilder length: 13 set new length: 20 new sequence: stringbuilder Example 3Test it NowOutput: string: stringbuilder length: 13 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.setLength(Unknown Source) at java.lang.StringBuilder.setLength(Unknown Source) at snippet.StringBuilderSetLengthExample3.main(StringBuilderSetLengthExample3.java:7)
Next TopicStringBuilder class
|