Java – Switch statement

‘switch’ statement can have multiple execution paths. It is similar to that of ‘if else-if’ statement except that switch can handle expressions which results to any primitive data type and if statements handle only boolean expressions.

Syntax:

switch (expression)

{

case ‘value1’:

//statements

break;

case ‘value2’:

//statements

break;

case ‘value3’:

//statements

break;

…

default:

//statements

}

The value of the expression is matched with the case values. Only the statements inside the matched case are executed.

The ‘break’ keyword is added after each case in order to exit from the switch case. If the ‘break’ keyword is not specified, all the cases would be checked and the matching cases would be executed.