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)

StringBuilder(String s)

StringBuilder(CharSequence cs)

Constructors
int length()

int capacity()

Returns the length and capacity (capacity is always greater or equal than length)
StringBuilder append(String s)

StringBuilder insert(int index, String s)

Adds characters to the end of the string (increase length if needed)
StringBuilder delete(int start)

StringBuilder delete(int start, int end)

Deletes characters from the string (decrease length)
void setLength(int n) If n < current length → Truncates string

If n > current length → Increases capacity (add null chars)

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 a StringBuilder object changes after each invocation to some of its methods:

StringBuilder sb = new StringBuilder(5);

Java StringBuilder Example - 01

  • capacity = 5
  • length = 0
  • string = ""
sb.append("ABCD");

Java StringBuilder Example - 02

  • capacity = 5
  • length = 4
  • string = "ABCD"
sb.setLength(2);

Java StringBuilder Example - 03

  • capacity = 5
  • length = 2
  • string = "AB"
sb.append("CDEFG");

Java StringBuilder Example - 04

 

  • capacity >= 7
  • length = 7
  • string = "ABCDEFG"

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.


Leave a Reply