From Java SE 12, a new and enhanced version of the switch statement is available. Consider the example below
switch (monthNum) {
case 2:
System.out.println("28 days");
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
System.out.println("31 days");
break;
case 4: case 6: case 9: case 11:
System.out.println("30 days");
}
Two keywords are repeated: case
many times, and break
twice (though break can appear many times in longer switch statements)
The enhanced switch statement allows us to seperate multiple case values using a comma, and, where the code is a sinlge line for a statement, doesn't require use of the of the break keyword - there is no fall through. The above code is rewritten below in the new format
switch (monthNum)
{
case 2 -> System.out.println("28 days");
case 1,3,5,7,8,10,12 -> System.out.println("31 days");
case 4, 6, 9, 11 -> System.out.println("30 days");
}
If, rather than printing the message showing the number of days in a week, we wanted to store it in a variable, instead of printing inside the switch statement, we could assign it to a variable, for example:
String message = "";
switch (monthNum)
{
case 2 -> message = "28 days";
case 1,3,5,7,8,10,12 -> message = "31 days";
case 4, 6, 9, 11 -> message = "30 days";
}
System.out.println(message);
This approach works with both the new and original switch statement
The enhanced statement allows us to go on step further and reduce the duplication of the message =
element of the code. Provided every possible case is considered, we can assign the result of calling the switch statement to a variable. In the above code, we only consider values from 1-12 inclusive, therefore to consider any other integer value, we need a default clause. Adding the default clause, and assigning to a variable would look like this:
String message = switch (monthNum)
{
case 2 -> "28 days";
case 1,3,5,7,8,10,12 -> "31 days";
case 4, 6, 9, 11 -> "30 days";
default -> "not a valid month number";
};
System.out.println(message);