Java Reference
In-Depth Information
The method
intValue()
recovers the corresponding
int
value from an object of
type
Integer
. This process of going from an object of a wrapper class to the corre-
sponding value of a primitive type is sometimes called
unboxing
, and as you will see
in the next subsection, you can let Java automatically do all the work of unboxing
for you.
The wrapper classes for the primitive types
byte
,
short
,
long
,
float
,
double
,
and
char
are
Byte
,
Short
,
Long
,
Float
,
Double
, and
Character
, respectively. The
methods for converting from the wrapper class object to the corresponding primi-
tive type are
intValue
for the class
Integer
, as we have already seen,
byteValue
for
the class
Byte
,
shortValue
for the class
Short
,
longValue
for the class
Long
,
floatValue
for the class
Float
,
doubleValue
for the class
Double
, and
charValue
for
the class
Character
.
unboxing
other
wrapper
classes
Wrapper Classes
Every primitive type has a corresponding wrapper class. A wrapper class allows you to have
a class object that corresponds to a value of a primitive type. Wrapper classes also contain a
number of useful predefined constants and static methods.
Automatic Boxing and Unboxing
Converting from a value of a primitive type, such as
int
, to a corresponding object of
its associated wrapper class, such as
Integer
, is called boxing. You can think of the
object as a “box” that contains the value of the primitive type. In fact, the wrapper
object does contain the value of the primitive type as the value of a private instance
variable. The following are examples of boxing:
Integer numberOfSamuri =
new
Integer(47);
Double price =
new
Double(499.99);
Character grade =
new
Character('A');
Starting with version 5.0, Java will automatically do this boxing and so the previous
three assignments can be written in the following equivalent, but simpler, forms:
automatic
boxing
Integer numberOfSamuri = 47;
Double price = 499.99;
Character grade = 'A';
This is an automatic type cast. What is actually done by Java is what we showed in the
forms using the
new
, but it is handy to be able to write the assignments in the simpler
form.