Java Reference
In-Depth Information
level is
VERBOSE
, all three output parts are printed; if
NORMAL
, two parts
are printed; and if
TERSE
, only one part is printed.
A
case
or
default
label does
not
force a break out of the
switch
. Nor does
it imply an end to execution of statements. If you want to stop execut-
ing statements in the switch block you must explicitly transfer control
out of the switch block. You can do this with a
break
statement. Within
a switch block, a
break
statement transfers control to the first statement
after the
switch
. This is why we have a
break
statement after the
TERSE
output is finished. Without the
break
, execution would continue through
into the code for the
default
label and throw the exception every time.
Similarly, in the
SILENT
case, all that is executed is the
break
because
there is nothing to print.
Falling through to the next case can be useful in some circumstances.
But in most cases a
break
should come after the code that a case label
selects. Good coding style suggests that you always use some form of
FALLTHROUGH
comment to document an intentional fall-through.
A single statement can have more than one
case
label, allowing a sin-
gular action in multiple cases. For example, here we use a
switch
state-
ment to decide how to translate a hexadecimal digit into an
int
:
public int hexValue(char ch) throws NonHexDigitException {
switch (ch) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return (ch - '0');
case 'a': case 'b': case 'c':
case 'd': case 'e': case 'f':
return (ch - 'a') + 10;
case 'A': case 'B': case 'C':
case 'D': case 'E': case 'F':
return (ch - 'A') + 10;
default: