Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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;
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.