|
| BASIC |
Just as the if statement provides a choice between two blocks of code, based on a boolean value, the switch statement provides a choice between several blocks of code, based on an integer value.
The syntax is fairly complex:
switch (integer_expression) { case integer_constant_1: statements; break; case integer_constant_2: statements; break; ... case integer_constant_N: statements; break; default: statements; break; }
where:
integer_expression must evaluate to one of the following
types: int, byte, short, long,
char (Java 5 also allows Integer, Byte,
Short, Long, Character, and Enum).integer_constant_x values must be either literal
values (such as 5) or constants
declared with the keyword final.statements may be any sequence of zero or more statements.
Notice that it is not necessary to use braces
to form the statements (along with the following break statement)
into a block, although this is sometimes done.break is intentional, otherwise you may
"correct" this problem at some later date.default case should come last. It is good style to always
include a default case, even if you believe that all possibilities have been
covered; in this case, you can put the statement assert false;
in the default case to document your belief.break statement in the last case is unnecessary. I think
it's good style to put a break in every case, but this opinion
is controversial.integer_expression is evaluated,
then compared against each case in order. When a matching integer_constant
is found, execution begins at the following statements, and
continues until either a break (or a return) is encountered,
or until the end of the switch statement.