next up previous
Next: Example of switch statement Up: Unit 05 Previous: Solution of the exercise

The switch statement

If we have to realize a multiple-choice selection we can use several nested if-else statements. Java has also a specific statement that can be used in specific cases to realize in a simpler way a multiple-choice selection.


switch statement (version with break)

Syntax:

switch (expression) {
  case label-1: statements-1
                 break;
  ...
  case label-n: statements-n
                 break;
  default: default-statements
}

Semantics:

  1. First, expression is evaluated.
  2. Then, the first i is found for which the value of label-i is equal to the value of expression.
  3. If there is such an i, then statements-i are executed;
    otherwise default-statements are executed.
  4. The execution continues with the statement immediately following the switch statement.

Example:

int i;
...
switch (i) {
  case 0: System.out.println("zero"); break;
  case 1: System.out.println("one"); break;
  case 2: System.out.println("two"); break;
  default: System.out.println("less than zero or greater than two");
}

When i is equal to 0 (respectively, 1, 2) then "zero" (respectively "one", "two") is printed; when i is less than 0 or greater than two, then "less than zero or greater than two" is printed.


Note: If we have more than one values of the expression for which we want to execute the same statements, we can group together different cases:

case label-1: case label-2: statements
                               break;


next up previous
Next: Example of switch statement Up: Unit 05 Previous: Solution of the exercise