Java Reference
In-Depth Information
This causes the value in
iOb
to be incremented. It works like this:
iOb
is unboxed, the
value is incremented, and the result is reboxed.
Because of auto-unboxing, you can use integer numeric objects, such as an
Integer
, to
control a
switch
statement. For example, consider this fragment:
When the
switch
expression is evaluated,
iOb
is unboxed and its
int
value is obtained.
As the examples in the program show, because of autoboxing/unboxing, using numeric
objects in an expression is both intuitive and easy. With early versions of Java, such code
would have involved casts and calls to methods such as
intValue( )
.
A Word of Warning
Because of autoboxing and auto-unboxing, one might be tempted to use objects such as
Integer
or
Double
exclusively, abandoning primitives altogether. For example, with auto-
boxing/unboxing it is possible to write code like this: