default: System.out.println("error");
}
When the switch expression is evaluated, iOb is unboxed and its int value is obtained.
As the examples in the program show, because of autoboxing/unboxing, using numeric
objects in an expression is both intuitive and easy. In the past, such code would have involved
casts and calls to methods such as intValue( ).
Autoboxing/Unboxing Boolean and Character Values
As described earlier, Java also supplies wrappers for boolean and char. These are Boolean
and Character. Autoboxing/unboxing applies to these wrappers, too. For example, consider
the following program:
// Autoboxing/unboxing a Boolean and Character.
class AutoBox5 {
public static void main(String args[]) {
// Autobox/unbox a boolean.
Boolean b = true;
// Below, b is auto-unboxed when used in
// a conditional expression, such as an if.
if(b) System.out.println("b is true");
// Autobox/unbox a char.
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
System.out.println("ch2 is " + ch2);
}
}
The output is shown here:
b is true
ch2 is x
The most important thing to notice about this program is the auto-unboxing of b inside
the if conditional expression. As you should recall, the conditional expression that controls
an if must evaluate to type boolean. Because of auto-unboxing, the boolean value contained
within b is automatically unboxed when the conditional expression is evaluated. Thus, with
the advent of autoboxing/unboxing, a Boolean object can be used to control an if statement.
Because of auto-unboxing, a Boolean object can now also be used to control any of Java's
loop statements. When a Boolean is used as the conditional expression of a while, for, or
do/while, it is automatically unboxed into its boolean equivalent. For example, this is now
perfectly valid code:
Boolean b;
// ...
while(b) { // ...
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home