Java 14 Switch表达式
Java 12引入了Switch语句中的表达式,并将其作为预览功能发布。Java 13在Switch语句中添加了一种新的yield结构,用于返回一个值。而在Java 14中,Switch表达式现在是一个标准特性。
- 每个case块可以使用yield语句返回一个值。
-
对于枚举类型,可以跳过default case。对于其他情况,default case是必需的。
示例
考虑以下示例 −
ApiTester.java
public class APITester {
public static void main(String[] args) {
System.out.println("Old Switch");
System.out.println(getDayTypeOldStyle("Monday"));
System.out.println(getDayTypeOldStyle("Saturday"));
System.out.println(getDayTypeOldStyle(""));
System.out.println("New Switch");
System.out.println(getDayType("Monday"));
System.out.println(getDayType("Saturday"));
System.out.println(getDayType(""));
}
public static String getDayType(String day) {
var result = switch (day) {
case "Monday", "Tuesday", "Wednesday","Thursday", "Friday": yield "Weekday";
case "Saturday", "Sunday": yield "Weekend";
default: yield "Invalid day.";
};
return result;
}
public static String getDayTypeOldStyle(String day) {
String result = null;
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
result = "Weekday";
break;
case "Saturday":
case "Sunday":
result = "Weekend";
break;
default:
result = "Invalid day.";
}
return result;
}
}
编译并运行程序
$javac APITester.java
$java APITester
输出
Old Switch
Weekday
Weekend
Invalid day.
New Switch
Weekday
Weekend
Invalid day.