Java Reference
In-Depth Information
Next we discuss the other decision-making control structure in Java: the switch
statement.
The switch Statement
The exam objectives state that you should be able to “develop code that implements a
switch statement and identify legal argument types.” A switch statement is a decision-
making control structure based on testing an integer value for equality to a list of
case statements. A switch is similar to an if-then-else statement, except that a switch
statement can only test for equality and it is possible for multiple blocks of code in a
switch to execute. Figure 3.2 shows the syntax of a switch statement.
The syntax of a switch statement
FIGURE 3.2
The switch keyword
Parentheses (required)
Beginning curly brace
switch( integer_variable ) {
case constantexpression :
statements ;
case constantexpression :
statements ;
The body of a
switch consists
of one or more
case statements.
...
default :
statements ;
The default
block is optional
and must
appear at the
end.
}
Ending curly brace
The following rules apply to using switch statements:
The integer_variable must be compatible with an int , which means you can only
switch on a byte , short , char , int , Byte , Short , Character , Integer , or an enum type.
Any number of case statements can appear.
The constantexpression of a case must be a literal value or a final variable.
The default block is optional and must appear at the end of all the case statements. If
none of the case statements equal the expression, the default block executes.
When a case is true, no other case statements are tested for equality, and all
statements following the case execute until a break occurs or the end of the switch
statement is reached.
Search WWH ::




Custom Search