Java Reference
In-Depth Information
Each case value is notionally compared with the value of an expression. If one matches then the code for
that case is executed, and the break branches to the first statement after the switch . As I said earlier, if you
don't include the break statements, the logic is quite different, as shown in Figure 3-5 .
FIGURE 3-5
Now when a case label value is equal to the switch expression, the code for that case is executed and
followed by the statements for all the other cases that succeed the case that was selected, including that for
the default case if that follows. This is not usually what you want, so make sure you don't forget the break
statements.
You can arrange to execute the same statements for several different case labels, as in the following
switch statement:
char yesNo = 'N';
// more program logic...
switch(yesNo) {
case 'n': case 'N':
System.out.println("No selected");
break;
case 'y': case 'Y':
System.out.println("Yes selected");
break;
}
Here the variable yesNo receives a character from the keyboard somehow. You want a different action
depending on whether the user enters "Y" or "N" , but you want to be able to accept either uppercase or
lowercase entries. This switch does just this by putting the case labels together. Note that there is no default
case here. If yesNo contains a character other than those identified in the case statements, the switch state-
ment has no effect. In practice, you might add a default case in this kind of situation to output a message
indicating when the value in yesNo is not valid.
Of course, you could also implement this logic using if statements:
 
 
Search WWH ::




Custom Search