- In this post, we are going to learn about recent enhancements to switch statement in Java.
- There are 4 enhancements to switch statement.
- List of case constants
- Switch expression
- yield statement
- case statement with arrow operator
List of case constants
Output:
Switch expression, yield statement:
- Switch expression is simply switch statement which can return a value.
- We can return a value using yield keyword. We can write above using switch expression and yield keyword as below.
- We must add semicolon at the end of switch expression. Because it is treated a statement.
- We no need to write break statement because yield returns value and exit from switch expression. If we write break statement, we get compiler error.
- Normally default is optional for switch. But default is mandatory for switch expression.
Case statement with arrow operator :
- We can use arrow operator after case statement in place of semicolon.
can be written as below.
case "JAN" ->
- Arrow operator case statement can be in below three forms.
case "JAN" -> { block of statements}
case "JAN" -> throw exception;
- We can directly return value from case statement. We don't need to use yield keyword.
- We don't need to use break because we exit from switch after returning value from switch.
- We must write default statement.
- When we use block , we must yield keyword to return value from switch expression.
- We don't need to use break statement. default statement is mandatory.
Conclusion:
These enhancements are really good addition to Java programming language. It optimizes the code. Thanks for reading . Happy Coding 😀.