Java 14 Switch Expressions

Java 14 introduces switch expressions to go along side the familiar switch statement.

String dayOfWeekName = switch ( dayNumber )
        {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6 -> "Saturday";
            case 7 -> "Sunday";
            default -> "Invalid day";
        };

return dayOfWeekName;
  • The new switch is an expression and as such returns a value
  • Colon replaced with ->, using this syntax, there is no need for the break keyword, as no fall-through
  • As it returns a value, all possibilities must be exhausted (can use default as catch all)

Each case can be a block of code and as such each block has its own scope, this was not the case with the switch statement. Multiple cases can be used.

return switch( dayNumber )
{
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend!!";

    default -> "Invalid day";
};

It’s possible to mix and match syntax (for switch statement and expression), but I am not a fan of that approach as it lacks clarity in my view.

I like this new addition, some modern languages already have no implicit fall-through, like Swift for example. With Java now supporting both and the possibility to mix syntax, unit tests for each case to protect against unintentional fall-though are as important as ever.