Java 12 introduced a new feature called Switch Expressions, which allows developers to use switch as an expression that returns a value, rather than just a statement. In this article, we’ll explore this new feature and see how it can be useful in Java programming.
Switch expressions in Java can be written in two forms, as a block or as an expression. Let’s look at each of these forms.
Switch Expressions as a Block
Switch expressions can be written as a block, which is similar to the traditional switch statement. Here’s an example:
public String getDayOfWeek(int day) {
String dayOfWeek = switch(day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> throw new IllegalArgumentException("Invalid day of the week: " + day);
};
return dayOfWeek;
}
In this example, we have a method called getDayOfWeek
that takes an integer parameter day
. We use switch expressions to match the value of day
to a corresponding day of the week string. If the value of day
is not in the range of 1 to 7, an IllegalArgumentException
is thrown.
Notice that in the switch expression, we use the arrow (->
) notation to separate the case label from the resulting value. We also use the default
case to handle any values that don’t match any of the other cases.
Switch Expressions as an Expression
Switch expressions can also be written as an expression, which allows us to use them in a more concise and readable way. Here’s an example:
public String getDayOfWeek(int day) {
return switch(day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> throw new IllegalArgumentException("Invalid day of the week: " + day);
};
}
In this example, we have the same method getDayOfWeek
that takes an integer parameter day
. Instead of using a variable to store the result, we return the result of the switch expression directly.
This form of switch expressions is useful when we want to use them in a more functional programming style, where we want to avoid side effects and return a value directly.
Conclusion
Switch expressions are a powerful addition to Java programming that allows us to write more concise and readable code. They can be used as both a block and an expression, depending on the context and our coding style. By using switch expressions, we can improve the quality of our code and make it easier to understand and maintain.