CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING
but many developers prefer switch statements. Also, a switch statement can be easier to debug, if your
debugger doesn't support conditional breakpoints. Fortunately for us, the debugger built into Eclipse
does support conditional breakpoints, as we will see in Chapter 11, “Debugging.”
One difference between if statements and switch blocks is that if statements evaluate only boolean
conditions. That is, the evaluation expression in an if statement must always resolve to true or false. A
switch block evaluates any value of the type used as its argument. Consequently, a switch block
evaluating int values evaluate any int value. In this way, switch blocks support any number of execution
paths versus the two paths (true and false) of an if statement.
Also, the switch statement evaluates only integers, String objects, and enumerations. If you have a
class that produces a set of other possibilities (such as a class that produces a different type of object for
each possible result), you need to use an if-else structure rather than a switch statement.
A switch statement requires a number of case labels, each of which forms a comparison with the
value defined as the switch statement's single argument. Let's consider Listing 5-5: creating a greeting
based on the time of day (same output as Listing 5-3, but with a switch statement).
Listing 5-5. Example switch statement
GregorianCalendar gregorianCalendar = new GregorianCalendar();
int hour = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
String greeting = "Good ";
switch(hour) {
case (1):
case (2):
case (3):
case (4):
case (5):
case (6):
case (7):
case (8):
case (9):
case (10):
case (11): {
greeting += "morning";
break;
}
case (12):
case (13):
case (14):
case (15):
case (16):
case (17): {
greeting += "afternoon";
break;
}
default: {
greeting += "evening";
break;
}
}
System.out.println(greeting );