What is Switch Expression in Java ?
Switch Expression is a new feature introduced in Java 12, which allows developers to use switch statements as expressions instead of just statements.
This means that a switch expression returns a value, which can be assigned to a variable or used in an expression.
Syntax:
The syntax of the switch expression in Java is:
1 2 3 4 5 6 |
result = switch (expression) { case value1 -> expression1; case value2 -> expression2; case value3, value4 -> expression3; default -> expression4; } |
Here, 'expression'
is the value that is being compared to the case values.
Each case value can be followed by an arrow case label '->'
and an expression that will be executed if the case value matches the 'expression'
.
If multiple case values have the same expression, they can be combined using a comma ','
.
The 'default'
keyword is used if none of the case values match the expression.
Example:
Here is an example of a switch expression in Java using arrow case labels :
1 2 3 4 5 6 7 8 9 |
int dayOfWeek = 2; String dayType = switch (dayOfWeek) { case 1, 2, 3, 4, 5 -> "Weekday"; case 6, 7 -> "Weekend"; default -> throw new IllegalArgumentException("Invalid day of week: " + dayOfWeek); }; System.out.println(dayType); |
In this example, we have a variable 'dayOfWeek'
that represents the day of the week.
We use a switch expression to determine whether it is a weekday or a weekend.
- If the value of
'dayOfWeek'
is between 1 and 5, it will match the first case and return the string"Weekday"
. - If the value is 6 or 7, it will match the second case and return the string
"Weekend"
. - If the value is not valid, it will throw an exception with an error message.
Output:
The output of this program will be:
Because the value of 'dayOfWeek'
is 2, which matches the first case of the switch expression.
Feature Timeline:
- First introduced in Java 12 as a preview feature.
- In Java 13, the
'break'
keyword was replaced by'yield'
. - Released as a final feature in Java 14 without any further changes.