3.2.5 switch

Previous Index Next


The switch statement transfers control to one of several statements depending on the value of an expression. The basic syntax is :
switch ( Expression )
 {
   case ExpressionValue: StatementToExecute
   case ExpressionValue: StatementToExecute
 }
For example:
int k = 1;

switch ( k)

{

 case 1: k = 0;

 case 2: k = 1;

 case 3: k = 2;

}
Since the switch statement is based on the C/C++ switch statement it has an odd behavior known as "falling through cases". What happens is that if a matching case is found then the statements for the case and ALL the cases below it will be executed. In the example above the final value of k would be 2.

To avoid "falling through" a case you can use the break statement. When Java encounters a break statement it will exit the switch statement.

For example :

int k = 1;

switch ( k)
{
 case 1: k = 0;
         break;  // exit switch
 case 2: k = 1;
         break;  // exit switch
 case 3: k = 2;
         break;  // exit switch
}