The most common form of the Java switch statement takes an integer (or a numeric type argument that can be automatically “promoted” to an integer type), a string type argument, or an “enum” type (discussed shortly) and selects among a number of alternative, constant case branches:3 switch ( expression )
{
case constantExpression :
statement;
[ case constantExpression :statement; ]
...
[ default :
statement; ]
}
The case expression for each branch must evaluate to a different constant integer or
string value at compile time. Strings are compared using the String equals() method,
which we’ll discuss in more detail soon. 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. But that’s not the end of the story. Perhaps counterintuitively,
the switch statement then continues 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:
int value = 2;
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:
int retValue = checkStatus();
switch ( retVal )
{
case MyClass.GOOD :
// something good
break;
case MyClass.BAD :
// something bad
break;
default :
// neither one
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:
int value = getSize();
switch( value ) {
case MINISCULE:
case TEENYWEENIE:
case SMALL:
System.out.println("Small" );
break;
case MEDIUM:
System.out.println("Medium" );
break;
case LARGE:
case EXTRALARGE:
System.out.println("Large" );
break;
}
This example effectively groups the six possible values into three cases.
0 comments:
Post a Comment