Java Reference
In-Depth Information
[true]
case a
case a actions(s)
break
[false]
[true]
case b
case b actions(s)
break
[false]
[true]
case z
case z actions(s)
break
[false]
default actions(s)
Fig. 5.10 | switch multiple-selection statement UML activity diagram with break statements.
The break statement is not required for the switch 's last case (or the optional
default case, when it appears last), because execution continues with the next statement
after the switch .
Error-Prevention Tip 5.8
Provide a default case in switch statements. This focuses you on the need to process ex-
ceptional conditions.
Good Programming Practice 5.3
Although each case and the default case in a switch can occur in any order, place the de-
fault case last. When the default case is listed last, the break for that case is not required.
Notes on the Expression in Each case of a switch
When using the switch statement, remember that each case must contain a constant inte-
gral expression—that is, any combination of integer constants that evaluates to a constant
integer value (e.g., -7, 0 or 221)—or a String . An integer constant is simply an integer val-
ue. In addition, you can use character constants —specific characters in single quotes, such
as 'A' , '7' or '$' —which represent the integer values of characters and enum constants (in-
troduced in Section 6.10). (Appendix B shows the integer values of the characters in the
ASCII character set, which is a subset of the Unicode ® character set used by Java.)
The expression in each case can also be a constant variable —a variable containing a
value which does not change for the entire program. Such a variable is declared with key-
word final (discussed in Chapter 6). Java has a feature called enum types, which we also
present in Chapter 6— enum type constants can also be used in case labels.
 
 
Search WWH ::




Custom Search