The switch statement

The switch statement has a similar purpose as the if-else-if statement, but is more restrictive in the condition that determines which block of statements is executed, and this is sometimes more appropriate. It is defined as this template (where [ ] means optional, and [[ ]] means optional, multiple times):

switch ( expr ) {
      case value-1a : [[ case value-1b : ]]
            body-1
            break;
      [[ case value-2a : [[ case value-2b : ]]
            body-2
            break;
      ]]
      [ default:
            body-def
      ]
}

where

  • expr is an expression that yields a byte, short, char, or int type, an enumerated type, or a String;
  • value-1a, value-1b, value-2a, value-2b, etc. are values that are of the same type as the type of expr;
  • body-1, body-2, body-def, etc. are blocks of zero or more statements;
  • When the switch statement finds a case value that is equal to expr, it executes the code in body.
  • The break statement terminates execution of the switch statement. If not present, execution continues with the code of the next case.
  • If the value of expr does not match the value of any case, the body of the default case is executed.

The following code is the switch version of the if-else-if code that prints the date, adding the appropriate “st”, “nd”, “rd”, or “th” suffix.

switch (date) {
   case 1:
   case 21:
   case 31:
      System.out.println(date + "st");
      break;
   case 2:
   case 22:
      System.out.println(date + "nd");
      break;
   case 3:
   case 23:
      System.out.println(date + "rd");
      break;
   default:
      System.out.println(date + "th");
}

Leaving out the break statement between cases is often a good idea, as in the example above. But it is also a source of bugs. The switch statement requires extra vigilance on your part to avoid this kind of bug.