Java12 - Switch 开关表达式

Java12 将表达式引入 Switch 语句并作为预览功能发布。 以下是在带有表达式的新开关的情况下引入的更改 −

  • 没有失败。
  • 不需要 break 语句来防止 fallthrough。
  • 一个案例可以有多个常量标签。
  • 默认大小写现在是强制性的。

考虑以下示例 −

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) {

      String result = switch (day) {
         case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> "Weekday";
         case "Saturday", "Sunday" -> "Weekend";
         default -> {
            break "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 -Xlint:preview --enable-preview -source 12 APITester.java

$java --enable-preview APITester

输出

Old Switch
Weekday
Weekend
Invalid day.
New Switch
Weekday
Weekend
Invalid day.