A StringBuilder
object is like a String
object but it can be modified. Internally it’s treated like a variable-length array that contains a sequence of characters: it has capacity
(max number of characters it can contain) and length
(number of characters of the string that the object represents).
StringBuilder Main Methods | |
---|---|
StringBuilder(int initCapacity)
|
Constructors |
int length()
|
Returns the length and capacity (capacity is always greater or equal than length) |
StringBuilder append(String s)
|
Adds characters to the end of the string (increase length if needed) |
StringBuilder delete(int start)
|
Deletes characters from the string (decrease length) |
void setLength(int n) |
If n < current length → Truncates string
If |
void ensureCapacity(int n) |
Sets capacity to at least n characters (but could be more) |
StringBuilder reverse() |
Reverses the string |
String toString() |
Returns a new String object containing the characters of the StringBuilder |
A Visual Example
The following example shows how aStringBuilder
object changes after each invocation to some of its methods:
StringBuilder sb = new StringBuilder(5);
|
|
sb.append("ABCD");
|
|
sb.setLength(2);
|
|
sb.append("CDEFG");
|
|
Remember: capacity >= length
(always).
The StringBuffer Class
StringBuffer
is the same as StringBuilder
but thread-safe (it’s safe for use by multiple threads because its methods are synchronized). Because of this, StringBuffer
operations are usually slower than StringBuilder
operations.