4.6 Control Statements and Unboxing
There are several control statements
in Java that take as an argument a
boolean value, or an expression that results to a boolean value. It
shouldn't be much of a surprise that these expressions now also take Boolean values. Additionally, the switch statement has an array of new
types it will accept.
4.6.1 How do I do that?
if/else, while, and do all are affected by Tiger's ability to unbox Boolean
values to boolean values. By now, this shouldn't require much explanation:
NOTEYou might want to
Boolean arriving = false;
Boolean late = true;
Integer peopleInRoom = 0;
int maxCapacity = 100;
boolean timeToLeave = false;
while (peopleInRoom < maxCapacity) {
if (arriving) {
System.out.println("It's good to see you.");
peopleInRoom++;
} else {
peopleInRoom--;
}
if (timeToLeave) {
do {
System.out.printf("Hey, person %d, get out!%n", peopleInRoom);
peopleInRoom--;
} while (peopleInRoom > 0);
}
}
be cautious running
this codeit's
actually an
infinite loop.There are several boxing and unboxing operations going on here, in several
control statements. Browse through this code, and work mentally
through each operation.Another statement that benefits from unboxing is switch. In pre-Tiger
JVMs, the switch statement accepts int, short, char, or byte values.
With unboxing in play, you can now supply it with Integer, Short, Char,
and Byte values as well, in addition to the introduction of enums.NOTEEnums are
covered in
Chapter 3.