Java Reference
In-Depth Information
8.6. Boxing Conversions
The automatic conversion of a variable of primitive type into an instance
of its wrapper class, is termed a
boxing conversion
the wrapper object
acts like a "box" in which the primitive value is held. The opposite conver-
sion, from an instance of a wrapper class to a primitive value, is termed
an
unboxing conversion.
A boxing conversion replaces any primitive value
v
with a wrapper object
of the same value. The wrapper object's type corresponds to the type of
v
. For example, given
Integer val = 3;
val
will refer to an
Integer
object because 3 is an
int
value;
val.intValue()
will return the value 3.
An unboxing conversion takes a reference to a wrapper object and ex-
tracts its primitive value. Building on the previous example,
int x = val;
is equivalent to the explicit
int x = val.intValue();
and the value of
x
is 3. If
val
was a
Short
reference, the unboxing of
val
would invoke
val.shortValue()
, and so forth. If a wrapper reference is
null
, an unboxing conversion will throw a
NullPointerException
.
The boxing and unboxing conversions are applied automatically in many
contexts, such as assignment and argument passing, so primitives and
reference types can be used almost interchangeably. However, the con-