站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

The switch Statement - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Language Basics

The switch Statement

Use the switch (in the glossary) statement to conditionally perform statements based on an integer expression or enumerated type. The following sample program, SwitchDemo (in a .java source file), declares an integer named month whose value supposedly represents the month in a date. The program displays the name of the month, based on the value of month, using the switch statement.
public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        switch (month) {
            case 1:  System.out.println("January"); break;
            case 2:  System.out.println("February"); break;
            case 3:  System.out.println("March"); break;
            case 4:  System.out.println("April"); break;
            case 5:  System.out.println("May"); break;
            case 6:  System.out.println("June"); break;
            case 7:  System.out.println("July"); break;
            case 8:  System.out.println("August"); break;
            case 9:  System.out.println("September"); break;
            case 10: System.out.println("October"); break;
            case 11: System.out.println("November"); break;
            case 12: System.out.println("December"); break;
            default: System.out.println("Not a month!");break;
        }
    }
}
The switch statement evaluates its expression, in this case the value of month, and executes the appropriate case (in the glossary) statement. Thus, the output of the program is August. Of course, you could implement this by using an if statement.
int month = 8;
if (month == 1) {
    System.out.println("January");
} else if (month == 2) {
    System.out.println("February");
}
. . . //and so on
Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use based on readability and other factors. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value. Also, the value provided to each case statement must be unique.

Another switch statement point of interest is the break (in the glossary) statement after each case. Each break statement terminates the enclosing switch statement, and the flow of control continues with the first statement following the switch block. The break statements are necessary because without them case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements. The following example, SwitchDemo2 (in a .java source file), illustrates why it might be useful to have case statements fall through.

public class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                numDays = 0;
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}
This is the output from the program.
Number of Days = 29
Technically, the final break is not required because flow would fall out of the switch statement anyway. However, we recommend using a break so that modifying the code is easier and less error-prone. Note that break can be used to terminate loops, as well; see the Branching Statements (in the Learning the Java Language trail) section.

Finally, you should use the default (in the glossary) statement at the end of the switch statement to handle all values that aren't explicitly handled by one of the case statements.

Enumerated Types in switch Statements

Enumerated types, a feature introduced in 5.0, can be used in switch statements. You'll learn all about enumerated types later, in the chapter Classes and Inheritance (in the Learning the Java Language trail). This section just shows how to use them in a switch statement; fortunately, it's just like using integers in a switch statement.

The following code from SwitchEnumDemo (in a .java source file) is almost identical to the code you saw previously from SwitchDemo2 (in a .java source file). It substitutes enumerated values for the integers, but otherwise the switch statement is the same.

public class SwitchEnumDemo {
    public enum Month { JANUARY, FEBRUARY, MARCH, APRIL,
                        MAY, JUNE, JULY, AUGUST, SEPTEMBER,
                        OCTOBER, NOVEMBER, DECEMBER }

    public static void main(String[] args) {
        Month month = Month.FEBRUARY;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case JANUARY:
            case MARCH:
            case MAY:
            case JULY:
            case AUGUST:
            case OCTOBER:
            case DECEMBER:
                numDays = 31;
                break;
            case APRIL:
            case JUNE:
            case SEPTEMBER:
            case NOVEMBER:
                numDays = 30;
                break;
            case FEBRUARY:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                numDays=0;
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}

This example shows just a bit of what the Java programming language's enumerations can do. To learn more, see the Enumerated Types (in the Learning the Java Language trail) section.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.