14.9
The
switch
Statement
BLOCKS AND STATEMENTS
If no
case
matches but there is a
default
label, then all statements after the
matching
default
label in the switch block, if any, are executed in sequence.
If all these statements complete normally, or if there are no statements after
the
default
label, then the entire
switch
statement completes normally.
If no
case
matches and there is no
default
label, then no further action is
taken and the
switch
statement completes normally.
If any statement immediately contained by the
Block
body of the
switch
statement completes abruptly, it is handled as follows:
If execution of the
Statement
completes abruptly because of a
break
with no
label, no further action is taken and the
switch
statement completes normally.
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 general rule for
labeled statements ( 14.6).
As in C and C++, execution of statements in a switch block falls through
labels in Java. 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:
276
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved