Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
// result is not reboxed.
i = iOb + (iOb / 3);
System.out.println("i after expression: " + i);

}
}


The output is shown here:


Original value of iOb: 100
After ++iOb: 101
iOb2 after expression: 134
i after expression: 134

In the program, pay special attention to this line:

++iOb;


This causes the value iniObto be incremented. It works like this:iObis unboxed, the
value is incremented, and the result is reboxed.
Auto-unboxing also allows you to mix different types of numeric objects in an expression.
Once the values are unboxed, the standard type promotions and conversions are applied. For
example, the following program is perfectly valid:


class AutoBox4 {
public static void main(String args[]) {


Integer iOb = 100;
Double dOb = 98.6;

dOb = dOb + iOb;
System.out.println("dOb after expression: " + dOb);
}
}


The output is shown here:

dOb after expression: 198.6

As you can see, both theDoubleobjectdOband theIntegerobjectiObparticipated
in the addition, and the result was reboxed and stored indOb.
Because of auto-unboxing, you can use integer numeric objects to control aswitch
statement. For example, consider this fragment:


Integer iOb = 2;


switch(iOb) {
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;


Chapter 12: Enumerations, Autoboxing, and Annotations (Metadata) 269

Free download pdf