Another selection structure to add to our repertoire is the switch/break structure. It is meant to provide a shorthand way of coding the following type of multiway selection structure:
if(integralVar == integralValue1)// some statementselseif(integralVar == integralValue2)// some statementselseif(integralVar == integralValue3)// some statementselse// some statements
Note that each of the conditions in this case involves the equality of an integral variable and an integral value. This type of structure occurs so frequently in programs that most languages contain statements specially designed to handle it. In Java, we use a combination of the switch and break statements to implement multiway selection.
switch(integralExpression){case integralValue1:// some statementscase integralValue2:// some statementscase integralValue3:// some statementsdefault:
some statements
}
The integralExpression must evaluate to a primitive integral value of type byte, short, int, char, or boolean. It may not be a long, float, double, or a class type. The integralValues must be literals or final variables. They serve as labels in the one or more case clauses that make up the switch statement body. The default clause is optional, but it is a good idea to include it.
int m =2;switch(m){case1:System.out.print(" m = 1");case2:System.out.print(" m = 2");case3:System.out.print(" m = 3");default:System.out.print(" default case");}
In this case, because m equals 2, the following output would be produced:
int m =2;if(m ==1)System.out.print(" m = 1");elseif(m ==2)System.out.print(" m = 2");elseif(m ==3)System.out.print(" m = 3");elseSystem.out.print(" default case");
The reason for this disparity is that the switch executes all statements following the label that matches the value of the integralExpression (see again Rule 3 above).
int m =2;switch(m){case1:System.out.print(" m = 1");break;case2:System.out.print(" m = 2");break;case3:System.out.print(" m = 3");break;default:System.out.print(" default case");}
In this example, the break statement causes control to pass to the end of the switch, with the effect being that one and only one case will be executed within the switch. Thus, the output of this code segment will be simply m = 2 , matching exactly the behavior of the multiway if-else selection structure (Figure 6.10.1).
Principle6.10.4.DEBUGGING TIP: Switch without break.
A common error in coding the switch-based multiway selection is forgetting to put a break statement at the end of each clause. This may cause more than one case to be executed.
Write a switch statement that checks an integer variable flavor and prints out the name of the ice cream flavor (where 0 is vanilla, 1 is chocolate, and 2 is strawberry) or prints “Error” in the default case. Test by changing the flavor variable’s value. Then, modify your solution to use constants (final variables) to represent the ice cream flavors.