Java Reference
In-Depth Information
21. keeper.addScore(two);
22. keeper.addScore(three);
23. keeper.printScores();
24. }
25. }
Within
main
, an
int
,
double
, and
float
are wrapped into their corresponding wrapper
class and passed into the
addScore
method of a new
ScoreKeeper
object. The code com-
piles because
Integer
,
Double
, and
Float
are subclasses of
Object
. Each object is saved in
the
ArrayList
, and invoking
printScores
generates the following output:
50
23.4
18.5
Parsing Strings Using the Wrapper Classes
Each wrapper class (except for
Character
) contains a useful method for parsing
String
objects into primitive types. The name of the method is
parse Xxx
, where
Xxx
is the data
type being parsed to. For example,
parseInt
in the
Integer
class parses a
String
to an
int
,
parseShort
in the
Short
class parses a
String
to a
short
, and so on. The following
statements parse a
String
into a
double
:
String s = ”123.4”;
double d = Double.parseDouble(s);
double twice = d * 2;
System.out.println(twice);
The
String
”123.4”
is parsed into a
double
, multiplied by
2
, and the output is
246.8
Each parse method throws a
NumberFormatException
if the given
String
does not
contain a value that is parseable to the appropriate type.
The wrapper classes are used whenever a primitive type needs to be treated as an
Object
. Java 5.0 introduced an autoboxing feature that hides the wrapper classes behind
the scenes. The next section discusses autoboxing and unboxing in detail.
Autoboxing and Unboxing
As of Java 5.0, you no longer need to write the code to wrap primitive types into their cor-
responding wrapper class; the compiler now does this for you behind the scenes. The term
Search WWH ::
Custom Search