Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

84 HOUR 7:Using Conditional Tests to Make Decisions


switch Statements
The ifand elsestatements are good for situations with two possible con-
ditions, but there are times when you have more than two conditions.
With the preceding grade example, you saw that ifand elsestatements
can be chained to handle several different conditions.
Another way to do this is with the switchstatement, which can test for a
variety of different conditions and respond accordingly. In the following
code, the grading example has been rewritten with a switchstatement:
switch(grade) {
case ‘A’:
System.out.println(“You got an A. Great job!”);
break;
case‘B’:
System.out.println(“You got a B. Good work!”);
break;
case‘C’:
System.out.println(“You got a C. What went wrong?”);
break;
default:
System.out.println(“You got an F. You’ll do well in Congress!”);
}

The first line of the switchstatement specifies the variable that is tested—
in this example, grade. Then, the switchstatement uses the {and }brack-
ets to form a block statement.
Each casestatementchecks the test variable in the switchstatement
against a specific value. The value used in a casestatement can be a char-
acter, an integer, or a string. In the preceding example, there are casestate-
ments for the characters A, B, and C. Each has one or two statements that
follow it. When one of these casestatements matches the variable in
switch, the computer handles the statements after the casestatement until
it encounters a breakstatement.
For example, if the gradevariable has the value of B, the text “You got a B.
Good work!” is displayed. The next statement is break, so nothing else in
the switchstatement is executed. The breakstatementtells the computer
to break out of the switchstatement.
The defaultstatement is used as a catch-all if none of the preceding case
statements is true. In this example, it occurs if the gradevariable does not
equal A, B, or C. You do not have to use a defaultstatementwith every
switchblock statement you use in your programs. If it is omitted, nothing
happens if none of the casestatements has the correct value.
Free download pdf