Java Reference
In-Depth Information
The switch Statement
Java uses a
switch statement
to evaluate an integer expression or value and
then conditionally perform statements. The switch statement evaluates its value
and then, depending on the value, transfers control to the appropriate
case
statement
. Control is transferred to a case statement that has a value following
the case keyword that matches the value evaluated by the switch statement. Table
4-9 displays the general form of the switch statement.
Table 4-9
The switch Statement
General form:
switch(value)
{
case value1:
. . . statements to execute if value matches value1
break;
case value2:
. . . statements to execute if value matches value2
break;
.
.
.
default:
. . . statements to execute if no match is found
}
Purpose:
To evaluate an integer expression or value and then conditionally perform statements. The
words
switch
,
case
,
break
, and
default
are reserved keywords. The switch value is any valid
integer data type, variable, or constant. The case value is any valid integer data type,
variable or constant. The switch statement compares the value to the case. If they match,
the code following that case statement is executed. The default case is optional and
executes only if none of the other, previous cases executes.
Example:
switch(flavor)
{
case 1:
System.out.println("chocolate");
break;
case 2:
System.out.println("vanilla");
break;
case 3:
System.out.println("strawberry");
break;
default:
System.out.println("Please choose one of our three flavors.");
}
As shown in Table 4-9, each case statement contains a
break statement
at
the end, which forces an exit of the structure when a match is found. After the
break, no more statements within the structure are evaluated, thereby reducing
processing time.
Search WWH ::
Custom Search