Java Reference
In-Depth Information
Adding to a StringBuffer Object
The
append()
method enables you to add a string to the end of the existing string stored in a
StringBuffer
object. This method comes in quite a few flavors, but perhaps the simplest adds a
String
constant to a
StringBuffer
object.
If we have defined a
StringBuffer
object with the statement:
StringBuffer aString = new StringBuffer("A stitch in time");
we can add to it with the statement:
aString.append(" saves nine");
after which
aString
will contain "
A
stitch
in
time
saves
nine
". The length of the string
contained in the
StringBuffer
object will be increased by the length of the string that you add. You
don't need to worry about running out of space though. If necessary, the capacity will be increased
automatically to accommodate the longer string.
The
append()
method returns the extended
StringBuffer
object, so you could also assign it to
another
StringBuffer
object. Instead of the previous statement, you could have written:
StringBuffer bString = aString.append(" saves nine");
Now both
aString
and
bString
point to the same
StringBuffer
object.
If you take a look at the operator precedence table back in Chapter 2, you will see that the '
.
' operator
(sometimes called the member selection operator) that we use to execute a particular method for an
object has left-to-right associativity. You could therefore write:
StringBuffer proverb = new StringBuffer(); // Capacity is 16
proverb.append("Many").append(" hands").append(" make").
append(" light").append(" work.");
The second statement is executed from left to right, so that the string contained in the object
proverb
is progressively extended until it contains the complete string.
Appending a Substring
Another version of the
append()
method will add part of a
String
object to a
StringBuffer
object. This version of
append()
requires you to specify two additional arguments: the index position
of the first character to be appended, and the total number of characters to be appended. This operation
is shown in the following diagram.