switch StatementPurpose:
- 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
breakstatement causes the program to proceed with the first statement after theswitchstructure. Thebreakstatement is used because otherwises thecases of the theswitchstatement would otherwise run together. Ifbreakis not used anywhere in aswitchstructure, then each time a match occurs in the structure, the statements for all the remainingcases 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
casecan have several statements. Curly brackets are not used even when acasehas more than one statement.
email suggestions to: cs015tas@cs.brown.edu
