THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

case Verbose.TERSE:
System.out.println(summaryState);
break;


default:
throw new IllegalStateException(
"verbosity=" + verbosity);
}
}


Once control has transferred to a statement following a case label, the following statements are executed in
turn, according to the semantics of those statements, even if those statements have their own different case
labels. The FALLTHROUGH comments in the example show where control falls through the next case label
to the code below. Thus, if the verbosity 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 executing 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 singular action in multiple cases. For
example, here we use a switch statement 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:
throw new NonHexDigitException(ch);
}
}


There are no break statements because the return statements exit the switch block (and the whole
method) before control can fall through.


You should terminate the last group of statements in a switch with a break, return, or throw, as you
would a group of statements in an earlier case. Doing so reduces the likelihood of accidentally falling through

Free download pdf