Java Reference
In-Depth Information
17
18
for
(
char
character : charArray)
19
System.out.print(character);
20
21
buffer.setCharAt(
0
,
'H'
);
buffer.setCharAt(
6
,
'T')
;
22
23
System.out.printf(
"%n%nbuffer = %s"
, buffer.toString());
24
25
buffer.reverse();
26
System.out.printf(
"%n%nbuffer = %s%n"
, buffer.toString());
27
}
28
}
// end class StringBuilderChars
buffer = hello there
Character at 0: h
Character at 4: o
The characters are: hello there
buffer = Hello There
buffer = erehT olleH
Fig. 14.12
|
StringBuilder
methods
charAt
,
setCharAt
,
getChars
and
reverse
. (Part 2
of 2.)
Class
StringBuilder
provides
overloaded
append
methods (Fig. 14.13) to allow values of
various types to be appended to the end of a
StringBuilder
. Versions are provided for
each of the primitive types and for character arrays,
String
s,
Object
s, and more. (Remem-
ber that method
toString
produces a string representation of any
Object
.) Each method
takes its argument, converts it to a string and appends it to the
StringBuilder
.
1
// Fig. 14.13: StringBuilderAppend.java
2
// StringBuilder append methods.
3
4
public class
StringBuilderAppend
5
{
6
public static void
main(String[] args)
7
{
8
Object objectRef =
"hello"
;
9
String string =
"goodbye"
;
10
char
[] charArray = {
'a'
,
'b'
,
'c'
,
'd'
,
'e'
,
'f'
};
11
boolean
booleanValue =
true
;
12
char
characterValue =
'Z'
;
13
int
integerValue =
7
;
14
long
longValue =
10000000000L
;
15
float
floatValue =
2.5f
;
16
double
doubleValue =
33.333
;
Fig. 14.13
|
StringBuilder
append
methods. (Part 1 of 2.)