next up previous
Next: Exercises Up: Unit 05 Previous: Observation on the switch

Omission of break (optional)

Actually, Java does not require that in each case of a switch statement the last statement is a break.

Hence, in general, the form of a switch statement is the following.


switch statement (general version)

Syntax:

switch (expression) {
  case label-1: statements-1
  ...
  case label-n: statements-n
  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, statements-i+1, ...are executed in sequence until the first break statement or the end of the switch statement;
    otherwise default-statements are executed.
  4. The execution continues with the statement immediately following the switch statement.

Example: More cases of a switch statement executed in sequence.

int sides;  //  maximum number of sides of a polygon (at most 6)
...
System.out.print("Polygons with at most " + sides + " sides: ");
switch (sides) {
  case 6: System.out.print("hexagon, ");
  case 5: System.out.print("pentagon, ");
  case 4: System.out.print("rectangle, ");
  case 3: System.out.println("triangle");
          break;
  case 2: case 1: System.out.println("none");
                  break;
  default: System.out.println;
           System.out.println;("Please input a value <= 6.");
}

If the value of sides is equal to 5, then the preceding code prints:

pentagon, rectangle, triangle

Note: When we omit the break statements, the order in which the various cases are written becomes important. This can easily cause errors.

Hence, it is a good programming practice to insert break as the last statement in each case.


next up previous
Next: Exercises Up: Unit 05 Previous: Observation on the switch