logo

Switch Expressions


Show

Java 12 launches the expressions to switch statements and announce it as a preview feature. After that Java 13 adds on the new yield to build up to give back a value from a switch statement. Now, new standard attributes in switch expressions are added with the release of Java 14.

  • Each case block can give back a value by making use of a yield statement.
  • In the case of enum, the default case can be jumped. In some other cases, a default case is needed.

Example

Examine the below given example:

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

Now, Compile and Run the program

$javac APITester.java
$java APITester

Output

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