Abstract

The switch statement provides a selection control structure to execute a selected section of code determined by the run-time value of an expression.  The condition is an expression which evaluates to a integer value, which include signed, char, enum, and even boolean values.

Selection statements are also referred to as conditional statements.  Other Java selection statements are the if statement and the if-else statement.

Usage

The switch statement is used to provide a multiway selection, based on an integral value.

Syntax

Syntax Diagrams

switch statement syntax diagram case syntax diagram

BNF

switch-statement
::= 'switch' '(' <expression> ')' '{' <case-list> '}'
case-list
::= <case>
::= <case-list> <case>
case
::= <case-label-list> <statement-list>
case-label
::= 'case' <static-expression> ':'
::= 'default' ':'

EBNF

switch-statement
::= 'switch' '(' <expression> ')' '{' <case> * '}'
case
::= <case-label> * <statement> *
case-label
::= 'case' <static-expression> ':'
 |  'default' ':'

Contextual Constraints

dynamic expression
The first expression (following the switch keyword) is called the controlling expression, and must be of an integral type.
static expression
The values of the case expressions must be unique; duplicate case values are a compile time error.
The static expression following the switch keyword should be type compatible with the controlling expression.
declaration
Declarations which preceed the first case cannot include an initializer.

Semantics

switch statement
The value of the controlling expression is compared to the values of the case clauses in turn, and if the controlling value is the same as the value of the switch expression, control is transferred to the statement following that case.
static expression
The expressions following the case keywords must be constant: they are evaluated statically at compile time.

Flowchart

Switch flowchart

Remarks

Reference Links

If Statement
If-Else Statement

Other Languages

C Now C Switch Statement
C++ Now C++ Switch Statement
COBOL Now COBOL Evaluate Statement
Java Now
Java Switch Statement
Pascal Now Pascal Case Statement
PHP Now PHP Switch Statement