Java Reference
In-Depth Information
Going the other way, from object type to primitive, is just as simple:
Integer wrapper - integer = 5; // primitive 5 autoboxed into
// an Integer
int primitive - int = wrapper - integer; // automatic unboxing
// Integer into int
These shortcuts simplify coding and reduce errors in J2SE 5.0, but you might
not be too impressed since the simplification is only minor. Note, though, that
autoboxing and unboxing can be used just about anywhere. They can even be used
in loop control and incrementing and decrementing operations. For a contrived
example, consider adding all the integers from 1 to 100:
public class Box {
public static void main (String[] args) {
int MAX = 100; // a primitive int type
Integer counter = 1; // an Integer type
Integer sum = 0;
// ditto
while (true) {
sum + = counter;
if (counter == MAX) break;
counter++;
}
System.out.println ("counter is now " +counter);
System.out.println ("sum is now " + sum);
System.out.println ("MAX*(MAX+1)/2 is " +
MAX*(MAX+1)/2);
}
} // class Box
There is a lot of hidden autoboxing and unboxing going on in this simple-looking
code. First, the Integer types counter and sum are autoboxed from the
primitive values 1 and 0 . Then, in the loop, they are unboxed to primitive values
so the + = operation can be applied and then reboxed to their “native” Integer
types. To do the == comparison counter is unboxed so it can be compared
with the int type MAX .Ifthe break does not apply, then counter is unboxed,
operated on with ++ , and then reboxed.
Autoboxing and unboxing work in a for loop as well:
Integer sum = 0;
for (Integer counter = 1; counter < MAX; counter++) {
sum + = counter;
}
Note that both of these loops are likely to perform abysmally because of all the
autoboxing and unboxing operations that must occur. Even though the conversions
do not appear explicitly in the source code, they still must be done. An optimizing
 
Search WWH ::




Custom Search