Java Reference
In-Depth Information
FIGURE 4.2
The sequence of characters increases by one each time through the loop.
alpha
String Builder object
'a' 'b' 'c' 'd' 'e'
.
.
.
alpha.append ('e')
j
The output of the code is
abcdefghijklmnopqrstuvwxyz
The principal methods of the
StringBuilder
and
StringBuffer
classes are their
append
and
insert
methods. The
append
and
insert
methods are overloaded to accept any of the
primitive types,
Object
,
String
, or
StringBuffer
. To demonstrate the method signatures, here
are the
append
and
insert
methods in
StringBuilder
for appending and inserting a
float
:
public StringBuilder append(float f)
appends the given
float
to the end of the
character sequence.
public StringBuilder insert(int offset, float f)
inserts the given
float
at the
value of the offset. The first index of the sequence is 0, the second index is 1, and so on.
The overloaded methods for the other data types take on the same form as the methods
above. The
append
and
insert
methods are identical in
StringBuffer
, except that the
return values are of type
StringBuffer
:
public StringBuffer append(float f)
public StringBuffer insert(int offset, float f)
The
append
method appends the data to the end of the character sequence, while the
insert
method inserts the data at the given offset. Notice that the return value of
append
and
insert
is the original
StringBuilder
or
StringBuffer
object, which allows for the
chaining of method calls. For example, see if you can fi gure out the character sequence that
the following code generates:
24. StringBuffer sb = new StringBuffer();
25. sb.append(“cet”).insert(2,”ntra”).insert(0,”con”).append(“ing”);
26. System.out.println(sb);
Let's break this code down step by step:
1.
The initial
StringBuffer
object instantiated on line 24 is empty.
2.
On line 25, the methods are executed left to right, so the first
append
call puts
”cet”
in the sequence.
Search WWH ::
Custom Search