switch Statements

The if and else statements are good for situations with only two possible conditions, but there are times when you have more than two options that need to be considered. With the preceding grade example, you saw that if and else statements can be chained to handle several different conditions. Another way to do this is to use the switch statement. You can use it in a Java program to test for a variety of different conditions and respond accordingly. In the following example, the grade example has been rewritten with the switch statement to handle a complicated range of choices:

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. You'll never get into a good "
 + "college!");
 break;
 default:
 System.out.println("You got an F. You'll do well in Congress!");
}


The first line of the switch statement specifies the variable that will be tested—in this example, grade. Then the switch statement uses the { and } brackets to form a block statement. Each of the case statements checks the test variable in the switch statement against a specific value. The value used in a case statement must be either a character or an integer. In this example, there are case statements for the characters 'A', 'B', and 'C'. Each of these has one or two statements that follow it. When one of these case statements matches the variable listed with switch, the computer handles the statements after the case statement until it encounters a break statement. For example, if the grade variable has the value of B, the text You got a B. Good work! will be displayed. The next statement is break, so no other part of the switch statement will be considered. The break statement tells the computer to break out of the switch statement. The default statement is used as a catch-all if none of the preceding case statements is true. In this example, it will occur if the grade variable does not equal 'A', 'B', or 'C'. You do not have to use a default statement with every switch block statement you use in your programs. If it is omitted, nothing will happen if none of the case statements has the correct value.

Watch Out!

One thing you might want to do with switch is to make each case statement represent a range of values. As an example, in a grading program, you might want to use an integer called numberGrade and test for case numberGrade > 89:. Unfortunately, this isn't possible in Java because each case statement must refer to a single value. You'll have to use a series of if statements or if-else statements when you aren't working with a bunch of different one-value conditions.


      
Comments