10.6 The 'StringBuffer' Class

In contrast to the String class, which implements immutable character strings, the StringBuffer class implements mutable character strings. Not only can the character string in a string buffer be changed, but the capacity of the string buffer can also change dynamically. The capacity of a string buffer is the maximum number of characters that a string buffer can accommodate before its size is automatically augmented.

Although there is a close relationship between objects of the String and StringBuffer classes, these are two independent final classes, both directly extending the Object class. Hence, String references cannot be stored (or cast) to StringBuffer references and vice versa. Both String and StringBuffer are thread-safe. String buffers are preferred when heavy modification of character strings is involved.

The StringBuffer class provides various facilities for manipulating string buffers:

  • constructing string buffers

  • changing, deleting, and reading characters in string buffers

  • constructing strings from string buffers

  • appending, inserting, and deleting in string buffers

  • controlling string buffer capacity

Constructing String Buffers

The final class StringBuffer provides three constructors that create and initialize StringBuffer objects and set their initial capacity.

StringBuffer(String s)

The contents of the new StringBuffer object are the same as the contents of the String object passed as argument. The initial capacity of the string buffer is set to the length of the argument string, plus room for 16 more characters.

StringBuffer(int length)

The new StringBuffer object has no content. The initial capacity of the string buffer is set to the value of the argument length, which cannot be less than 0.

StringBuffer()

This constructor also creates a new StringBuffer object with no content. The initial capacity of the string buffer is set for 16 characters.


Examples of StringBuffer object creation and initialization:

StringBuffer strBuf1 = new StringBuffer("Phew!");      // "Phew!", capacity 21
StringBuffer strBuf2 = new StringBuffer(10);           // "", capacity 10
StringBuffer strBuf3 = new StringBuffer();             // "", capacity 16

Reading and Changing Characters in String Buffers

int length()

Returns the number of characters in the string buffer.

char charAt(int index)
void setCharAt(int index, char ch)

These methods read and change the character at a specified index in the string buffer, respectively. The first character is at index 0 and the last one at index one less than the number of characters in the string buffer. A StringIndexOutOfBoundsException is thrown if the index is not valid.


The following is an example of reading and changing string buffer contents:

StringBuffer strBuf = new StringBuffer("Javv");           // "Javv", capacity 20
strBuf.setCharAt(strBuf.length()-1, strBuf.charAt(1));    // "Java"

Constructing Strings from String Buffers

The StringBuffer class overrides the toString() method from the Object class. It returns the contents of a string buffer in a String object.

String fromBuf = strBuf.toString();                       // "Java"

Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.

Appending, Inserting, and Deleting Characters in String Buffers

Appending, inserting, and deleting characters automatically results in adjustment of the string buffer's capacity, if necessary. The indices passed as arguments in the methods must be equal to or greater than 0. A StringIndexOutOfBoundsException is thrown if an index is not valid.

Appending Characters to a String Buffer

The overloaded method append() can be used to append characters at the end of a string buffer.

StringBuffer append(Object obj)

The obj argument is converted to a string as if by the static method call String.valueOf(obj), and this string is appended to the current string buffer.

StringBuffer append(String str)
StringBuffer append(char[] str)
StringBuffer append(char[] str, int offset, int len)
StringBuffer append(char c)

These methods allow characters from various sources to be appended at the end of the current string buffer.

StringBuffer append(boolean b)
StringBuffer append(int i)
StringBuffer append(long l)
StringBuffer append(float f)
StringBuffer append(double d)

These methods convert the primitive value of the argument to a string by applying the static method String.valueOf() to the argument, before appending the result to the string buffer:


Inserting Characters in a String Buffer

The overloaded method insert() can be used to insert characters at a given position in a string buffer.

StringBuffer insert(int offset, Object obj)
StringBuffer insert(int offset, String str)
StringBuffer insert(int offset, char[] str)
StringBuffer insert(int offset, char c)
StringBuffer insert(int offset, boolean b)
StringBuffer insert(int offset, int i)
StringBuffer insert(int offset, long l)
StringBuffer insert(int offset, float f)
StringBuffer insert(int offset, double d)

The argument is converted, if necessary, by applying the static method String.valueOf(). The offset argument specifies where the characters are to be inserted and must be greater than or equal to 0.


Deleting Characters in a String Buffer

The following methods can be used to delete characters from specific positions in a string buffer:

StringBuffer deleteCharAt(int index)
StringBuffer delete(int start, int end)

The first method deletes a character at a specified index in the string buffer, contracting the string buffer by one character. The second method deletes a substring, which is specified by the start index (inclusive) and the end index (exclusive).


Among other miscellaneous methods included in the class StringBuffer is the following method, which reverses the contents of a string buffer:

StringBuffer reverse()


Examples of appending, inserting, and deleting in string buffers:

StringBuffer buffer = new StringBuffer("banana split");   // "banana split"
buffer.delete(4,12);                                      // "bana"
buffer.append(42);                                        // "bana42"
buffer.insert(4,"na");                                    // "banana42"
buffer.reverse();                                         // "24ananab"
buffer.deleteCharAt(buffer.length()-1);                   // "24anana"
buffer.append('s');                                       // "24ananas"

All the previous methods modify the contents of the string buffer and also return a reference value denoting the string buffer. This allows chaining of method calls. The method calls invoked on the string buffer denoted by the reference buffer can be chained as follows, giving the same result:

buffer.delete(4,12).append(42).insert(4,"na").reverse().
       deleteCharAt(buffer.length()-1).append('s');       // "24ananas"

The method calls in the chain are evaluated from left to right, so that the previous chain of calls is interpreted as follows:

(((((buffer.delete(4,12)).append(42)).insert(4,"na")).reverse()).
     deleteCharAt(buffer.length()-1)).append('s');        // "24ananas"

Each method call returns the reference value of the modified string buffer. This value is used to invoke the next method. The string buffer remains denoted by the reference buffer.

The compiler uses string buffers to implement the string concatenation, +. The following example code of string concatenation

String str1 = 4 + "U" + "Only";                                    // (1) "4UOnly"

is equivalent to the following code using one string buffer:

String str2 = new StringBuffer().
                  append(4).append("U").append("Only").toString(); // (2)

The code at (2) does not create any temporary String objects when concatenating several strings, since a single StringBuffer object is modified and finally converted to a String object.

Controlling String Buffer Capacity

int capacity()

Returns the current capacity of the string buffer, that is, the number of characters the current buffer can accommodate without allocating a new, larger array to hold characters.

void ensureCapacity(int minCapacity)

Ensures that there is room for at least minCapacity number of characters. It expands the string buffer, depending on the current capacity of the buffer.

void setLength(int newLength)

This method ensures that the actual number of characters, that is, length of the string buffer, is exactly equal to the value of the newLength argument, which must be greater than or equal to 0. This operation can result in the string being truncated or padded with null characters ('\u0000').

This method only affects the capacity of the string buffer if the value of the parameter newLength is greater than current capacity.

One use of this method is to clear the string buffer:

buffer.setLength(0);      // Empty the buffer.