switch Statement

Purpose:

To execute one of any number of mutually exclusive blocks of statements, depending on the value of an expression.

Mechanics:

switch( <selector> ) {
case <value 1> :
<statement 1>;
break;
case <value 2> :
<statement 2>;
break;
case <value n> :
<statement n>;
break;
default :
<statement n+1>
break;
}

Example:

switch (num) {
case 1 :
/* statements */
break;
case 2 :
/* statements */
break;
case 3 :
/* statements */
break;
default:
/* statements */
break;
}

Usage:

  • <selector> is an expression of ordinal type such as integer, char, or an enumerated type.
  • <value 1>, <value 2>,..., <value n> are integers or characters, or groups of integers or characters separated by commas.
  • <statement 1>, <statement 2>,..., <statement n>, <statement n+1> are legal java statements.
  • The break statement causes the program to proceed with the first statement after the switch structure. The break statement is used because otherwises the cases of the the switch statement would otherwise run together. If break is not used anywhere in a switch structure, then each time a match occurs in the structure, the statements for all the remaining cases will be executed.

Restrictions:

  • The <selector> is evaluated. If one of the values matches the <selector>, then the corresponding <statement> is executed.
  • If the <selector> does not match any of the values, then the default statement (<statement n+1>) is executed.
  • Each case can have several statements. Curly brackets are not used even when a case has more than one statement.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu