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 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.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
。