Java Reference
In-Depth Information
In the switch statement, the selection is determined by the value of an expression that you specify,
which is enclosed between the parentheses after the keyword switch . In this case it's the variable wash
that would need to be previously declared as of type char , byte , short or int . You define the
possible switch positions by one or more case values , also called case labels , which are defined using the
keyword case . All the case labels for a switch are enclosed between the braces for the switch
statement and they can appear in any order. We have used three case values in the example above. A
particular case value is selected if the value of the switch expression is the same as that of the
particular case value.
When a particular case is selected, the statements which follow that case label are executed. So if wash
has the value 2, the statements that follow:
case 2: // wash is 2 for Linen
are executed. In this case, these are:
System.out.println("Linen selected");
break;
When a break statement is executed here, it causes execution to continue with the statement following
the closing brace for the switch . The break is not mandatory, but if you don't put a break statement
at the end of the statements for a case, the statements for the next case in sequence will be executed as
well, through to whenever another break is found or the end of the switch block is reached. This is not
usually what you want. The break after the default statements in our example is not strictly
necessary, but it does protect against the situation when you might add another case label at the end of
the switch statement block, and overlook the need for the break at the end of the last case.
There is a case label for each handled choice in the switch , and they must all be unique. The
default case we have in the example above is, in general, optional. It is selected when the value of the
expression for the switch does not correspond with any of the case values that have been defined. If
you don't specify a default case and the value of the switch expression does not match any of the
case labels, execution continues at the statement following the closing brace of the switch statement.
Search WWH ::




Custom Search