Switch Enhancements in Java

  • In this post, we are going to learn about recent enhancements to switch statement in Java.
  • There are 4 enhancements to switch statement.

    1. List of case constants
    2. Switch expression
    3. yield statement
    4. case statement with arrow operator    

List of case constants

  • If we want execute same block of code for some switch case constants , we write like below.


Output:





  • The above example can be re-written using list of constants like below.

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.
    case "JAN" :
    can be written as below.
    case "JAN" ->
  • Arrow operator case statement can be in below three forms.
        case "JAN" -> expression;
        case "JAN" -> { block of statements}
        case "JAN" -> throw exception;
  • Let's look at few examples using arrow operator .


  • 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 😀.




No comments:

Post a Comment

Different ways to run Spring boot App

 What are the different ways to run Spring boot app ?