Autoboxing/Unboxing Helps Prevent Errors
In addition to the convenience that it offers, autoboxing/unboxing can also help prevent
errors. For example, consider the following program:
// An error produced by manual unboxing.
class UnboxingError {
public static void main(String args[]) {
Integer iOb = 1000; // autobox the value 1000
int i = iOb.byteValue(); // manually unbox as byte !!!
System.out.println(i);
// does not display 1000 !
}
}
This program displays not the expected value of 1000, but 24! The reason is that the value
­
inside iOb is manually unboxed by calling byteValue( ), which causes the truncation of the
value stored in iOb, which is 1,000. This results in the garbage value of 24 being assigned
­
to i. Auto-unboxing prevents this type of error because the value in iOb will always auto-
unbox into a value compatible with int.
In general, because autoboxing always creates the proper object, and auto-unboxing
always produces the proper value, there is no way for the process to produce the wrong
type of object or value. In the rare instances where you want a type different than that
produced by the automated process, you can still manually box and unbox values. Of
course, the benefits of autoboxing/unboxing are lost. In general, new code should employ
autoboxing/unboxing. It is the way that modern Java code will be written.
A Word of Warning
Now that Java includes autoboxing and auto-unboxing, some might be tempted to use objects
such as Integer or Double exclusively, abandoning primitives altogether. For example, with
autoboxing/unboxing it is possible to write code like this:
// A bad use of autoboxing/unboxing!
Double a, b, c;
a = 10.0;
b = 4.0;
c = Math.sqrt(a*a + b*b);
System.out.println("Hypotenuse is " + c);
In this example, objects of type Double hold values that are used to calculate the hypotenuse
of a right triangle. Although this code is technically correct and does, in fact, work properly,
it is a very bad use of autoboxing/unboxing. It is far less efficient than the equivalent code
written using the primitive type double. The reason is that each autobox and auto-unbox
adds overhead that is not present if the primitive type is used.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home