Java Reference
In-Depth Information
StringBuffer aString = new StringBuffer("A stitch in time");
You can add to it with the statement:
aString.append(" saves nine");
After this
aString
contains
"A stitch in time saves nine"
. The length of the string contained in the
StringBuffer
object is increased by the length of the string that you add. You don't need to worry about
running out of space though. The capacity is always increased automatically whenever necessary to accom-
modate the longer string.
The
append()
method returns a reference to 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 in Chapter 2, you see that the
'.'
operator (sometimes
called the member selection operator) that you use to execute a particular method for an object has left-to-
right associativity. You can therefore write multiple append operations in a single statement:
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. The reference that each call to
append()
returns
is used to call
append()
again for the same object,
proverb
.
Appending a Substring
Another version of the
append()
method adds part of a
String
or a
StringBuffer
object to a
StringBuffer
object. This version of
append()
requires three arguments: a reference to the
String
or
StringBuffer
object from which the substring to be appended is obtained, the index position of the first
character in the object for the substring that is to be appended, and the index position of one past the last
character to be appended. If you supply
null
as the first argument, the substring from will be extracted from
the string
"null"
.
To illustrate the workings of this, suppose you create a
StringBuffer
object and a
String
object with
the following statements:
StringBuffer buf = new StringBuffer("Hard ");
String aString = "Waxworks";
You can then append part of the
aString
object to the
buf
object with this statement:
buf.append(aString, 3, 7);
This operation is shown in
Figure 4-13
.