SEARCH BY

All

  • All
  • Java8
  • Spring

Switch expressions in java 14

Post a Comment

Introduction

Switch statement is different than Switch expression. Switch statements cannot return any value, but switch expression ( in java14 ) return a value by break, yield or arrow ( -> ).
Switch expression in java14 must yield a value or throw an exception while using switch result to assign as a value to variable.

Traditional Switch Statement

Traditional switch statement uses break to end block of a CASE and can not return any value.


/**
 * @author John Smith <john.smith@example.com>
*/
package l2f.gameserver.model;

public abstract strictfp class L2Char extends L2Object {
  public static final Short ERROR = 0x0001;

  public void moveTo(int x, int y, int z) {
    _ai = null;
    log("Should not be called");
    if (1 > 5) { // wtf!?
      return;
    }
  }
}

int day = 4;
String dayAsString="";
switch (day) {
  case 1:
    dayAsString="Monday";
    break;
  case 2:
    dayAsString="Tuesday";
    break;
  case 3:
    dayAsString="Wednesday";
    break;
  case 4:
    dayAsString="Thursday";
    break;
  case 5:
    dayAsString="Friday";
    break;
  case 6:
    dayAsString="Saturday";
    break;
  case 7:
    dayAsString="Sunday";
    break;
  default:
    dayAsString="enter day between 1 and 7";
}
int day = 4;
String dayAsString="";
switch (day) {
  case 1:
    dayAsString="Monday";
    break;
  case 2:
    dayAsString="Tuesday";
    break;
  case 3:
    dayAsString="Wednesday";
    break;
  case 4:
    dayAsString="Thursday";
    break;
  case 5:
    dayAsString="Friday";
    break;
  case 6:
    dayAsString="Saturday";
    break;
  case 7:
    dayAsString="Sunday";
    break;
  default:
    dayAsString="enter day between 1 and 7";
}
Grouping Cases in a traditional switch statement
String vehicleType="car";
int noOfWheels;
switch (day) {
  case "car":
  case "van":
  case "jeep":
    noOfWheels=4;
    break;
  case "bike":
    noOfWheels=2;
    break;
  case "auto":
    noOfWheels=3;
    break;
}
Grouping cases will reduce number of times using break statement.

Switch expressions

Arrow operator ( -> ) is using in switch expression where as colon ( : ) is using in switch statement.
int day = 4;
String dayAsString="";
switch (day) {
  case 1 -> dayAsString="Monday";

  case 2 -> dayAsString="Tuesday";
   
  case 3 -> dayAsString="Wednesday";

  case 4 -> dayAsString="Thursday";
 
  case 5 -> dayAsString="Friday";
 
  case 6 -> dayAsString="Saturday";
  
  case 7 -> dayAsString="Sunday";
   
  default -> dayAsString="enter day between 1 and 7";
}
In the above variable dayAsString assigned at each case, instead that we can just rewrite the above code into following where switch expression will return ( yield )a value to variable dayAsString.
int day = 4;
String dayAsString= switch (day) {
  case 1-> "Monday";   
  
  case 2 -> "Tuesday";
  
  case 3 -> "Wednesday";
  
  case 4 -> "Thursday";
 
  case 5 -> "Friday";

  case 6 -> "Saturday";

  case 7 -> "Sunday";

  default -> "enter day between 1 and 7" ;
}
In the above code we are returning value using arrow operator ( -> ). In line 2 we are assigning switch expression result as a value to a variable dayAsString.

Grouping in Switch expression / Multiple Case labels

We can group multiple cases in a single executable block with switch expression
String vehicleType="car";
int noOfWheels = switch (day) {

  case "car", "van", "jeep" ->4;
  
  case "bike" -> 2;

  case "auto" -> 3;

  default -> throw new IllegalStateException("invalid vehicle name");
}

yield statement to return value

In switch expressions ( in java14) we can return a value from switch expression by using yield statement.
String vehicleType="car";
int noOfWheels = switch (day) {

  case "car", "van", "jeep" -> yield 4;
  
  case "bike" -> 
  		yield 2;

  case "auto" ->
  		yield 3;

  default -> {
  System.out.println("invalid input");
  yield 0;  
  };
}
In the above code we have used yield statement to return value for each case of switch expression.

Multiple coding lines with arrow operator

We can execute multiple coding lines for cases in switch expressions. We can enclose coding statements between { and } for each case to execute multiple coding lines.
String vehicleType="car";
int noOfWheels = switch (day) {

  case "car", "van", "jeep" ->  {
  System.out.println("print some value");
  // you can write your logic as per requirement
  yield 4;
  
  }
  
  case "bike" ->  {
  System.out.println("print some value");
  // you can write your logic as per requirement
  yield 2;
  
  }

  case "auto" ->
  		yield 3;

  default -> {
  System.out.println("invalid input");
  yield 0;  
  };
}

Mandatory yield statement

When switching case is yielding a value then each and evry case block must yeild a value to avoid error.
int day=3;
String dayAsString = switch (day) {
    case 1 -> {
        System.out.println("Monday"); 
        // ERROR! Block doesn't contain a yield statement
    }
     case 2 -> {
        System.out.println("Tuesday"); 
        yield "Tuesday"
    }
    // remaining code
    default -> 
    yield "invalid day";
};

default case with switch expression

To be exhaustiveness we must add default case when we are yielding a value as a result of switch expression
String vehicleType="lorry";
int noOfWheels = switch (day) {

  case "car", "van", "jeep" -> yield 4;
  
  case "bike" -> 
  		yield 2;

  case "auto" ->
  		yield 3;
}
In the above code vehicleType is lorry which is not covered in switch expression, in this case we can get an error, so to avoid this error which happens due to uncovered case ( lorry ) we need to setup default case
String vehicleType="lorry";
int noOfWheels = switch (day) {

  case "car", "van", "jeep" -> yield 4;
  
  case "bike" -> 
  		yield 2;

  case "auto" ->
  		yield 3;

  default -> {
  System.out.println("invalid input");
  yield 0;  
  };
}
In the above code we have used default case to execute some statements when we provide uncovered input for case that is lorry in our example then we can get invalid input message along with 0 as a value for noOfWheels variable.

References

https://docs.oracle.com/en/java/javase/14/language/switch-expressions.html
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox