Java 12 Switch case enhancements | Switch expression, yield keyword, optional fall through i.e. avoid break

In Java 12, switch-case statement has been improved as part of ‘Java Enhancement Proposal’ JEP 305 (JDK-8222184). Lets look at examples of these improvements.

Setup for preview feature

Switch enhancements in JDK 12 are preview only features i.e. these enhancements are not enabled by default. If you directly write code to use this, it will give compiler error Switch Expressions is a preview feature and disabled by default. Use --enable-preview to enable

If you are using eclipse IDE, then right click on project > Properties > Java Compiler > Uncheck “Use default compliance settings” > Check “Enable preview feature for Java 12”

After enabling preview feature, compiler will continue to give warning You are using a preview language feature that may or may not be supported in a future release  wherever preview features are used.


Arrow Labels without fall through

  • In addition to case X: (colon), new syntax introduced i.e. case X ->  (arrow)
  • case X: (colon) will fall-through i.e. if no break; found, then it will go to next  case Y:. case X ->  (arrow) will not fall-through i.e. it will only execute code of right on arrow & will end switch. It won’t go to next case so no need of break.
  • If case (arrow) has multiple lines of code, then use code block as shown in case ‘0’ in below example. Otherwise JDK will give compiler error Syntax error on token ";", SwitchLabels expected after this token
  • Case styles i.e. “:” & “->” can not be combined in single switch as JDK will give compiler error Mixing of different kinds of case statements '->' and ':' is not allowed within a switch



Switch Expression

Switch expression allows switch to be used directly to assign value using assignment operator or also in method arguments.

Switch expression must cover all possible values of variable used in switch like ‘enum’. Not doing so will cause a compilation error as shown below.



Yield keyword

If multiple lines of code is required with switch expression, yield keyword can be used to provide final value to assignment. Yield can also be used with regular switch case (colon) to use it as switch expression.



Leave a Reply

Your email address will not be published. Required fields are marked *