Java Reference
In-Depth Information
You use the
switch
statement to select from multiple choices that are identified by a set of fixed values for
a given expression. The expression that selects a choice must produce a result of an integer type other than
long
, or a value of an enumeration type, or a string. Thus, the expression that controls a
switch
statement
can result in a value of type
char
,
byte
,
short
, or
int
, an enumeration constant, or a
String
object.
In normal use the
switch
statement operates rather like a rotary switch in that you can select one of a
fixed number of choices. For example, on some makes of washing machine you choose between the various
machine settings in this way, with positions for cotton, wool, synthetic fiber, and so on, which you select by
turning the knob to point to the option that you want.
Here's a
switch
statement reflecting this logic for a washing machine:
switch(wash) {
case 1: // wash is 1 for Cotton
System.out.println("Cotton selected");
// Set conditions for cotton...
break;
case 2: // wash is 2 for Linen
System.out.println("Linen selected");
// Set conditions for linen...
break;
case 3: // wash is 3 for Wool
System.out.println("Wool selected");
// Set conditions for wool...
break;
default: // Not a valid value for wash
System.out.println("Selection error");
break;
}
The selection in the
switch
statement is determined by the value of the expression that you place between
the parentheses after the keyword
switch
. In this case it's simply the integer variable
wash
that would need
to be previously declared as of type
char
,
byte
,
short
, or
int
. You define the possible
switch
options by
one or more
case values
, also called
case labels
, which you define using the keyword
case
. In general, a
case label consists of the
case
keyword followed by a constant value that is the value that selects the case,
followed by a colon. The statements to be executed when the case is selected follow the case label. You
place all the case labels and their associated statements between the braces for the
switch
statement. You
have three case values in the example, plus a special case with the label
default
, which is another keyword.
A particular case value is selected if the value of the
switch
expression is the same as that of the particular
case value. The
default
case is selected when the value of the
switch
expression does not correspond to
any of the values for the other cases. Although I've written the cases in the preceding
switch
sequenced by
their case values, they can be in any order.
When a particular case is selected, the statements that 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");
// Set conditions for linen...
break;