3.4. The switch Statement
You use the switch statement to select from multiple choices based on a set of fixed values for a given expression. The expression must produce a result of an integer type other than long, or a value of an enumeration type. Thus, the expression that controls a switch statement can result in a value of type char, byte, short, or int, or an enumeration constant.
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 possible 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");
break;
case 2: // wash is 2 for Linen
System.out.println("Linen selected");
break;
case 3: // wash is 3 for Wool
System.out.println("Wool selected");
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 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access