Java Reference
In-Depth Information
any expression that evaluates to an integer, character, or string value. For example, it
might evaluate to a 32-bit integer or to a 16-bit character.
Eachcasebeginswithreservedword case ,continueswithaliteralvalueandacolon
character ( : ), continues with a statement to execute, and optionally concludes with a
break statement, which causes execution to continue after the switch statement.
After evaluating the selector expression , switch compares this value with
each case's value until it finds a match. If there is a match, the case's statement is
executed. For example, if the selector expression 's value matches value1 ,
statement1 executes.
Theoptionalbreakstatement(anythingplacedinsquarebracketsisoptional),which
consistsofreservedword break followedbyasemicolon,preventstheflowofexecu-
tion from continuing with the next case's statement. Instead, execution continues with
the first statement following switch.
Note Youwillusuallyplaceabreakstatementafteracase'sstatement.Forgettingto
includebreakcanleadtoahard-to-findbug.However,therearesituationswhereyou
want to group several cases together and have them execute common code. In such a
situation, you would omit the break statement from the participating cases.
Ifnoneofthecases' valuesmatch the selector expression 'svalue,andifa
defaultcase(signifiedbythe default reservedwordfollowedbyacolon)ispresent,
the default case's statement is executed.
The following example demonstrates this statement:
switch (direction)
{
case 0: System.out.println("You are travelling north.");
break;
case 1: System.out.println("You are travelling east.");
break;
case 2: System.out.println("You are travelling south.");
break;
case 3: System.out.println("You are travelling west.");
break;
default: System.out.println("You are lost.");
}
Search WWH ::




Custom Search