Documentation

The Java™ Tutorials
Hide TOC
The switch Statementswitch语句
Trail: Learning the Java Language
Lesson: Language Basics
Section: Control Flow Statements

The switch Statementswitch语句

Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths.if-thenif-then-else语句不同,switch语句可以有许多可能的执行路径。A switch works with the byte, short, char, and int primitive data types.switch使用byteshortcharint基元数据类型。It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).它还适用于枚举类型(在枚举类型中讨论)、String类和一些包装某些基本类型的特殊类:CharacterByteShortInteger(在数字和字符串中讨论)。

The following code example, SwitchDemo, declares an int named month whose value represents a month.下面的代码示例SwitchDemo声明了一个名为monthint,其值表示一个月。The code displays the name of the month, based on the value of month, using the switch statement.该代码使用switch语句根据month的值显示月份的名称。

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

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

In this case, August is printed to standard output.在本例中,August打印为标准输出。

The body of a switch statement is known as a switch block.switch语句的主体称为switch块A statement in the switch block can be labeled with one or more case or default labels.switch块中的语句可以使用一个或多个casedefault标签进行标记。The switch statement evaluates its expression, then executes all statements that follow the matching case label.switch语句计算其表达式,然后执行匹配case标签后面的所有语句。

You could also display the name of the month with if-then-else statements:您还可以使用if-then-else语句显示月份名称:

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 if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.决定是使用if-then-else语句还是switch语句取决于可读性和语句测试的表达式。An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.if-then-else语句可以基于值或条件的范围测试表达式,而switch语句仅基于单个整数、枚举值或字符串对象测试表达式。

Another point of interest is the break statement.另一个有趣的问题是break语句。Each break statement terminates the enclosing switch statement.每个break语句终止封闭的switch语句。Control flow continues with the first statement following the switch block.控制流继续执行switch块后面的第一条语句。The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.break语句是必需的,因为如果没有它们,switch块中的语句就会失效:匹配的case标签之后的所有语句都会按顺序执行,而不管后续case标签的表达式如何,直到遇到break语句为止。The program SwitchDemoFallThrough shows statements in a switch block that fall through.程序SwitchDemoFallThroughswitch块中显示失效的语句。The program displays the month corresponding to the integer month and the months that follow in the year:该程序显示与整数month对应的月份以及一年中接下来的月份:

public class SwitchDemoFallThrough {

    public static void main(String[] args) {
        java.util.ArrayList<String> futureMonths =
            new java.util.ArrayList<String>();

        int month = 8;

        switch (month) {
            case 1:  futureMonths.add("January");
            case 2:  futureMonths.add("February");
            case 3:  futureMonths.add("March");
            case 4:  futureMonths.add("April");
            case 5:  futureMonths.add("May");
            case 6:  futureMonths.add("June");
            case 7:  futureMonths.add("July");
            case 8:  futureMonths.add("August");
            case 9:  futureMonths.add("September");
            case 10: futureMonths.add("October");
            case 11: futureMonths.add("November");
            case 12: futureMonths.add("December");
                     break;
            default: break;
        }

        if (futureMonths.isEmpty()) {
            System.out.println("Invalid month number");
        } else {
            for (String monthName : futureMonths) {
               System.out.println(monthName);
            }
        }
    }
}

This is the output from the code:这是代码的输出:

August
September
October
November
December

Technically, the final break is not required because flow falls out of the switch statement.从技术上讲,不需要最终的break,因为流不在switch语句中。Using a break is recommended so that modifying the code is easier and less error prone.建议使用break,以便修改代码更容易,更不容易出错。The default section handles all values that are not explicitly handled by one of the case sections.default部分处理未由其中一个case部分显式处理的所有值。

The following code example, SwitchDemo2, shows how a statement can have multiple case labels.下面的代码示例SwitchDemo2显示了语句如何具有多个case标签。The code example calculates the number of days in a particular month:代码示例计算特定月份的天数:

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:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}

This is the output from the code:这是代码的输出:

Number of Days = 29

Using Strings in switch Statements在switch语句中使用字符串

In Java SE 7 and later, you can use a String object in the switch statement's expression.在Java SE 7和更高版本中,可以在switch语句的表达式中使用String对象。The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:以下代码示例StringSwitchDemo根据名为monthString的值显示月份数:

public class StringSwitchDemo {

    public static int getMonthNumber(String month) {

        int monthNumber = 0;

        if (month == null) {
            return monthNumber;
        }

        switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1;
                break;
            case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "april":
                monthNumber = 4;
                break;
            case "may":
                monthNumber = 5;
                break;
            case "june":
                monthNumber = 6;
                break;
            case "july":
                monthNumber = 7;
                break;
            case "august":
                monthNumber = 8;
                break;
            case "september":
                monthNumber = 9;
                break;
            case "october":
                monthNumber = 10;
                break;
            case "november":
                monthNumber = 11;
                break;
            case "december":
                monthNumber = 12;
                break;
            default: 
                monthNumber = 0;
                break;
        }

        return monthNumber;
    }

    public static void main(String[] args) {

        String month = "August";

        int returnedMonthNumber =
            StringSwitchDemo.getMonthNumber(month);

        if (returnedMonthNumber == 0) {
            System.out.println("Invalid month");
        } else {
            System.out.println(returnedMonthNumber);
        }
    }
}

The output from this code is 8.此代码的输出为8

The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used.switch表达式中的字符串与每个case标签关联的表达式进行比较,就好像使用了String.equals方法一样。In order for the StringSwitchDemo example to accept any month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase.为了让StringSwitchDemo示例接受任何月份,而不考虑大小写,month被转换为小写(使用toLowerCase方法),并且与大小写标签关联的所有字符串都是小写的。

Note: This example checks if the expression in the switch statement is null.注意:此示例检查switch语句中的表达式是否为nullEnsure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.确保任何switch语句中的表达式都不是null,以防止引发NullPointerException


Previous page: The if-then and if-then-else Statements
Next page: The while and do-while Statements