The addition of autoboxing and auto-unboxing greatly streamlines the coding of several
algorithms, removing the tedium of manually boxing and unboxing values. It also helps
prevent errors. Moreover, it is very important to generics, which operates only on objects.
Finally, autoboxing makes working with the Collections Framework (described in Part II)
much easier.
With autoboxing it is no longer necessary to manually construct an object in order to
wrap a primitive type. You need only assign that value to a type-wrapper reference. Java
automatically constructs the object for you. For example, here is the modern way to construct
an Integer object that has the value 100:
Integer iOb = 100; // autobox an int
Notice that no object is explicitly created through the use of new. Java handles this for you,
automatically.
To unbox an object, simply assign that object reference to a primitive-type variable.
For example, to unbox iOb, you can use this line:
int i = iOb; // auto-unbox
Java handles the details for you.
Here is the preceding program rewritten to use autoboxing/unboxing:
// Demonstrate autoboxing/unboxing.
class AutoBox {
public static void main(String args[]) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb);
// displays 100 100
}
}
Autoboxing and Methods
In addition to the simple case of assignments, autoboxing automatically occurs whenever
a primitive type must be converted into an object; auto-unboxing takes place whenever an
object must be converted into a primitive type. Thus, autoboxing/unboxing might occur when
an argument is passed to a method, or when a value is returned by a method. For example,
consider this example:
// Autoboxing/unboxing takes place with
// method parameters and return values.
class AutoBox2 {
// Take an Integer parameter and return
// an int value;
static int m(Integer v) {
return v ; // auto-unbox to int
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home