Main Page

Previous Next

The switch Statement

The switch statement enables you to select from multiple choices based on a set of fixed values for a given expression. The expression must produce a result of type char, byte, short or int, but not long, otherwise the statement will not compile. In normal use it 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.

A switch statement reflecting this logic would be:

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;
}

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.

We can illustrate the logic of the general switch statement in a flow chart.

Click To expand

Each case value is notionally compared with the value of an expression. If one matches then the code for that case is executed and the break branches to the first statement after the switch. As we said earlier, if you don't include the break statements, the logic is quite different, as shown next.

Click To expand

Now when a case label value is equal to the switch expression, the code for that case is executed, and we fall through to execute all the other cases that follow, including that for the default case if that follows. This is not usually what you want, so make sure you don't forget the break statements.

You can arrange to execute the same statements for several different case labels, as in the following switch statement:

char yesNo = 'N';
// more program logic…

switch(yesNo) {
  case 'n':
  case 'N':
       System.out.println("No selected");
       break;
  case 'y':
  case 'Y':
       System.out.println("Yes selected");
       break;
}

Here the variable yesNo receives a character from the keyboard somehow. You want a different action depending on whether the user enters 'Y' or 'N' but you want to be able to accept either uppercase or lowercase entries. This switch does just this by putting the case labels together. Note that there is no default case here. If yesNo contains a character other than those identified in the case statements, the switch statement has no effect. You might add a default case in this kind of situation to output a message to indicate that the value in yesNo is not valid.

Of course, you could also implement this logic using if statements:

if(yesNo=='n' || yesNo=='N') {
  System.out.println("No selected");

} else {
  if(yesNo=='y' || yesNo=='Y') {
    System.out.println("Yes selected");
  }
}

I prefer the switch statement as I think it's easier to follow, but you decide for yourself.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor