Java Reference
In-Depth Information
• If execution of the
Statement
completes abruptly for any other reason, the
switch
statement completes abruptly for the same reason.
The case of abrupt completion because of a
break
with a label is handled by the
Example 14.11-1. Fall-Through in the
switch
Statement
As in C and C++, execution of statements in a
switch
block “falls through labels.”
For example, the program:
class TooMany {
static void howMany(int k) {
switch (k) {
case 1: System.out.print("one ");
case 2: System.out.print("too ");
case 3: System.out.println("many");
}
}
public static void main(String[] args) {
howMany(3);
howMany(2);
howMany(1);
}
}
contains a
switch
block in which the code for each
case
falls through into the code for
the next
case
. As a result, the program prints:
many
too many
one too many
If code is not to fall through
case
to
case
in this manner, then
break
statements should be
used, as in this example:
class TwoMany {
static void howMany(int k) {
switch (k) {
case 1: System.out.println("one");
break; // exit the switch
case 2: System.out.println("two");
break; // exit the switch