Java 13

Java 13 – Switch Expressions

Java 12 introduces expressions to Switch statement and released it as a preview feature. Java 13 added a new yield construct to return a value from switch statement. It is still a preview feature.

Consider the following example −

Java13Switch.java

Example

public class Java13Switch {

   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 -> "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;
   }
}

Output

Compile the class using javac compiler as follows −

>javac -Xlint:preview --enable-preview -source 13 Java13Switch.java

>java --enable-preview Java13Switch

It should produce the following output −

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

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs