public static void main(String args[]) {
// Pass an int to m() and assign the return value
// to an Integer.  Here, the argument 100 is autoboxed
// into an Integer.  The return value is also autoboxed
// into an Integer.
Integer iOb = m(100);
System.out.println(iOb);
}
}
This program displays the following result:
100
In the program, notice that m( ) specifies an Integer parameter and returns an int result.
Inside main( ), m( ) is passed the value 100. Because m( ) is expecting an Integer, this value
is automatically boxed. Then, m( ) returns the int equivalent of its argument. This causes v
to be auto-unboxed. Next, this int value is assigned to iOb in main( ), which causes the int
return value to be autoboxed.
Autoboxing/Unboxing Occurs in Expressions
In general, autoboxing and unboxing take place whenever a conversion into an object or from
an object is required. This applies to expressions. Within an expression, a numeric object is
automatically unboxed. The outcome of the expression is reboxed, if necessary. For example,
consider the following program:
// Autoboxing/unboxing occurs inside expressions.
class AutoBox3 {
public static void main(String args[]) {
Integer iOb, iOb2;
int i;
iOb = 100;
System.out.println("Original value of iOb: " + iOb);
// The following automatically unboxes iOb,
// performs the increment, and then reboxes
// the result back into iOb.
++iOb;
System.out.println("After ++iOb: " + iOb);
// Here, iOb is unboxed, the expression is
// evaluated, and the result is reboxed and
// assigned to iOb2.
iOb2 = iOb + (iOb / 3);
System.out.println("iOb2 after expression: " + iOb2);
// The same expression is evaluated, but the
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home