Java14 - Switch 表达式语句
Java 12 将表达式引入 Switch 语句并作为预览功能发布。 Java 13 添加了一个新的 yield 结构来从 switch 语句返回一个值。 在 Java14 中,switch 表达式现在是一项标准功能。
每个 case 块都可以使用 yield 语句返回一个值。
如果是枚举,可以跳过默认大小写。 在其他情况下,需要 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.