Javatpoint Logo
Javatpoint Logo

Java StringBuilder setLength() method

The 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:

DataType Parameter Description
int newLength It is a new length of character sequence.

Returns:

NA

Exception:

IndexOutOfBoundsException - if the newLength argument is negative.

Compatibility Version:

Java 1.5 and above

Example 1

Test it Now

Output:

string: stringbuilder
length: 13
set new length: 6
new sequence: string

Example 2

Test it Now

Output:

string: stringbuilder
length: 13
set new length: 20
new sequence: stringbuilder

Example 3

Test it Now

Output:

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)






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA