The most common form of the switch statement takes an integer type argument (or an argument that can be automatically promoted to an integer type) and selects among a number of alternative integer constant case branches:
public void switchStatement(int expression)
{
switch( expression )
{
case int constantExpression:
statement;
[ case int constantExpression:
statement; ]
...
[ default:
statement; ]
}
}
The case expression for each branch must evaluate to a different constant integer value during compiling. An optional default case can be specified to catch unmatched conditions. When executed, the switch simply finds the branch matching its conditional expression (or the default branch) and executes the corresponding statement. The switch statement can then continue executing branches after the matched branch until it hits the end of the switch or a special statement called break. Here are a couple of examples:
public void test(int value)
{
switch ( value ) {
case 1:
System.out.println( 1 );
case 2:
System.out.println( 2 );
case 3:
System.out.println( 3 );
}
// prints 2, 3
}
Using break to terminate each branch is more common:
public void test(int retVal)
{
switch ( retVal )
{
case MyClass.GOOD:
...
break;
case MyClass.BAD:
...
break;
defult:
...
break;
}
}
In this example, only one branch: GOOD, BAD, or the default is executed. The "fall through" behavior of the switch is justified when you want to cover several possible case values with the same statement, without resorting to a bunch of if-else statements:
public void test(int value)
{
switch( value ) {
case 1:
case 2:
case 3:
System.out.println("3" );
break;
case 4:
System.out.println("4" );
break;
case 5:
case 6:
System.out.println("6" );
break;
}
}
This example effectively groups the six possible values into three cases.
I hope this has helped you. Please post comments.