Java – Switch Expressions


Java – Switch Expressions


”;


Using switch expressions, we can return a value and we can use them within statements like other expressions. We can use case L -> label to return a value or using yield, we can return a value from a switch expression.

Java 12 introduces expressions to Switch statements and releases them as a preview feature. Java 13 added a new yield construct to return a value from a switch statement. With Java 14, switch expression now is a standard feature.

  • Each case block can return a value using yield statement.

  • In case of enum, default case can be skipped. In other cases, default case is required.

Switch Expression Using “case L ->” Labels

Java provides a new way to return a value from a switch expression using case L – > notation.

Syntax

case label1, label2, ..., labeln -> expression;|throw-statement;|block 

Where label1 to labeln are representing the various values to compare and we can use expression, a statement to return a value or throw an expression.

Once Java runtime matches any label in the left block to the arrow, it moves to the right block of arrow and executes the expression(statement) and returns the result.

Switch Expression Example: Using case L -> Labels

In this example, we”ve compared switch expressions vs switch statement. getDayType() method takes a string input and returns the corresponding entry by evaluation switch expression and returning the value. Whereas getDayTypeOldStyle() method uses switch statement to compare each cases, uses break statement to end switch cases and to get a value, we”ve to set value in a variable.

package com.tutorialspoint;

public class SwitchTester {
   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) {
      // evaluate switch expression and get a value 
      return switch (day) {
         case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> "Weekday";
         case "Saturday", "Sunday" -> "Weekend";
         default -> "Invalid day.";
      };
   }

   public static String getDayTypeOldStyle(String day) {
      String result = null;
	  // evaluate relevant cases and get a value into result variable 
      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

Let us compile and run the above program, this will produce the following result −

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

Switch Expression Using “case L:” Statements and the yield Statement

In java, we can get a value from switch expressio and switch statement using yield statement. yield statement returns the value and finishes the switch execution.

Syntax

case label1, label2, ..., labeln -> expression; yield value;

case label1:
case labeln: expression; 
   yield value;

Switch Expression Example: Using “case L:” Statements and the yield Statement

Where label1 to labeln are representing the various values to compare and we can use expression to perform an operation and return value using yield statement.

In this example, we”ve compared switch expressions using yield statements. getDayType() method is using a switch expression with yield statement to get the result whereas getDayTypeStyle1() method is using switch cases with colon(:) notation with yield statement to the get the desired result.

package com.tutorialspoint;

public class SwitchTester {
   public static void main(String[] args) {
      System.out.println("Old Way");
      System.out.println(getDayTypeStyle2("Monday"));
      System.out.println(getDayTypeStyle2("Saturday"));
      // System.out.println(getDayTypeStyle2(""));

      System.out.println("New Way");
      System.out.println(getDayType("Monday"));
      System.out.println(getDayType("Saturday"));
      System.out.println(getDayType(""));
   }

   public static String getDayType(String day) {
      return switch (day) {
         // we can use block statements to return a value using yield after 
         // executing other statements		 
         case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> {
            System.out.println("In Weekdays");
            yield "Weekday"; 
         }
         case "Saturday", "Sunday" -> { 
            System.out.println("In Weekends");
            yield "Weekend"; 
         }
         default -> throw new IllegalStateException("Invalid day: " + day);
      };
   }

   public static String getDayTypeStyle2(String day) {
      return switch (day) {
         case "Monday":
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
         case "Friday":
            yield "Weekday";           
         case "Saturday": 
         case "Sunday":
            yield "Weekend";
         default:
            throw new IllegalStateException("Invalid day: " + day);         
      };
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Old Way
Weekday
Weekend
New Ways
In Weekdays
Weekday
In Weekends
Weekend
Exception in thread "main" java.lang.IllegalStateException: Invalid day: 
	at com.tutorialspoint.SwitchTester.getDayType(SwitchTester.java:26)
	at com.tutorialspoint.SwitchTester.main(SwitchTester.java:13)

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *