Java Reference
In-Depth Information
25
System.out.printf(
"int = %s%n"
,
String.valueOf(integerValue)
String.valueOf(longValue)
String.valueOf(floatValue)
);
26
System.out.printf(
"long = %s%n"
,
);
27
System.out.printf(
"float = %s%n"
,
);
28
System.out.printf(
29
String.valueOf(doubleValue)
String.valueOf(objectRef)
"double = %s%n"
,
);
30
System.out.printf(
"Object = %s"
,
);
31
}
32
}
// end class StringValueOf
char array = abcdef
part of char array = def
boolean = true
char = Z
int = 7
long = 10000000000
float = 2.5
double = 33.333
Object = hello
Fig. 14.9
|
String
valueOf
methods. (Part 2 of 2.)
There are seven other versions of method
valueOf
, which take arguments of type
boolean
,
char
,
int
,
long
,
float
,
double
and
Object
, respectively. These are demon-
strated in lines 21-30. The version of
valueOf
that takes an
Object
as an argument can
do so because all
Object
s can be converted to
String
s with method
toString
.
[
Note:
Lines 12-13 use literal values
10000000000L
and
2.5f
as the initial values of
long
variable
longValue
and
float
variable
floatValue
, respectively. By default, Java
treats integer literals as type
int
and floating-point literals as type
double
. Appending the
letter
L
to the literal
10000000000
and appending letter
f
to the literal
2.5
indicates to the
compiler that
10000000000
should be treated as a
long
and
2.5
as a
float
. An uppercase
L
or lowercase
l
can be used to denote a variable of type
long
and an uppercase
F
or low-
ercase
f
can be used to denote a variable of type
float
.]
We now discuss the features of class
StringBuilder
for creating and manipulating
dynam-
ic
string information—that is,
modifiable
strings. Every
StringBuilder
is capable of stor-
ing a number of characters specified by its
capacity
. If a
StringBuilder
's capacity is
exceeded, the capacity expands to accommodate the additional characters.
Performance Tip 14.3
Java can perform certain optimizations involving
String
objects (such as referring to one
String
object from multiple variables) because it knows these objects will not change.
String
s (not
StringBuilder
s) should be used if the data will not change.
Performance Tip 14.4
In programs that frequently perform string concatenation, or other string modifications,
it's often more efficient to implement the modifications with class
StringBuilder
.