Java Reference
In-Depth Information
The reverse conversion from an object of a wrapper class to a value of its associated
primitive type is called unboxing. Unboxing is also done automatically in Java (start-
ing in version 5.0). The following are examples of automatic unboxing:
automatic
unboxing
Integer numberOfSamuri =
new
Integer(47);
int
n = numberOfSamuri;
Double price =
new
Double(499.99);
double
d = price;
Character grade =
new
Character('A');
char
c = grade;
Java automatically applies the appropriate accessor method (
intValue
,
doubleValue
,
or
charValue
in these cases) to obtain the value of the primitive type that is assigned to
the variable. So the previous examples of automatic unboxing are equivalent to the fol-
lowing code, which is what you had to write in older versions of Java that did not do
automatic unboxing:
Integer numberOfSamuri =
new
Integer(47);
int
n = numberOfSamuri.intValue();
Double price =
new
Double(499.99);
double
d = price.doubleValue();
Character grade =
new
Character('A');
char
c = grade.charValue();
Our previous examples involved either only automatic boxing or only auto-
matic unboxing. That was done to simplify the discussion by allowing you to see
each of automatic boxing and automatic unboxing in isolation. However, code can
often involve a combination of automatic boxing and unboxing. For example,
consider the following code, which uses both automatic boxing and automatic
unboxing:
Double price = 19.90;
price = price + 5.12;
This code is equivalent to the following, which is what you had to write in older ver-
sions of Java that did not do automatic boxing and unboxing:
Double price =
new
Double(19.90);
price =
new
Double(price.doubleValue() + 5.12);
Automatic boxing and unboxing applies to parameters as well as the simple assign-
ment statements we just discussed. You can plug in a value of a primitive type, such as
a value of type
int
, for a parameter of the associated wrapper class, such as
Integer
.
Similarly, you can plug a wrapper class argument, such as an argument of type
Integer
, for a parameter of the associated primitive type, such as
int
.