The switch keyword is used along with the keyword case, and sometimes the keyword default, to create a conditional statement. In a switch statement, the switch keyword is followed by an expression within parentheses whose value must evaluate to a primitive Java data type. Once the expression has been evaluated, its value is compared against the label following each case statement within the switch statement body. When a label has the same value, the lines following that case statement are executed. An optional default label is included within the body of a switch statement when there is no guarantee that the labels provided by each case statement are the only values the switch expression may evaluate to.
The following example shows a typical switch statement construct:
switch ( someExpression )
{
case 1:
{
doCase1( );
break;
}
case 2:
{
doCase2( );
break;
}
case 3:
{
doCase3A( );
doCase3B( );
}
default:
doDefault( );
}
The break keyword is also, at times, used within the body of a switch statement. Once the lines following a case statement have executed, the break statement is included to jump over the remaining body of the switch condition. Without a break statement, subsequent case statements would continue being evaluated, and eventually the default statement, if one were included, would execute.