Java StringBuilder setLength() Method
Example
Keep only the first 5 characters:
StringBuilder sb = new StringBuilder("Hello World");
sb.setLength(5);
System.out.println(sb);
Definition and Usage
The setLength() method sets the number of characters in a StringBuilder.
If the new length is shorter, the text is cut. If it is longer, null characters (\u0000) are added to the end.
Tip: Use setLength(0) to empty a StringBuilder.
Syntax
public void setLength(int newLength)
Parameter Values
| Parameter | Description |
|---|---|
| newLength | Required. The new number of characters. |
Technical Details
| Throws: | IndexOutOfBoundsException - if newLength is negative. |
|---|
Related Pages
❮ StringBuilder Methods