The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Unlike 与if-then and if-then-else statements, the switch statement can have a number of possible execution paths.if-then和if-then-else语句不同,switch语句可以有许多可能的执行路径。A switch works with the byte, short, char, and int primitive data types.switch使用byte、short、char和int基元数据类型。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类和一些包装某些基本类型的特殊类:Character、Byte、Short和Integer(在数字和字符串中讨论)。
The following code example, 下面的代码示例SwitchDemo, declares an int named month whose value represents a month.SwitchDemo声明了一个名为month的int,其值表示一个月。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块中的语句可以使用一个或多个case或default标签进行标记。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 onDeciding 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.SwitchDemoFallThrough在switch块中显示失效的语句。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
In Java SE 7 and later, you can use a 在Java SE 7和更高版本中,可以在String object in the switch statement's expression.switch语句的表达式中使用String对象。The following code example, 以下代码示例StringSwitchDemo, displays the number of the month based on the value of the String named month:StringSwitchDemo根据名为month的String的值显示月份数:
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语句中的表达式是否为null。Ensure that the expression in any 确保任何switch statement is not null to prevent a NullPointerException from being thrown.switch语句中的表达式都不是null,以防止引发NullPointerException。