Switch Case in Java 12The switch case in Java has undergone some modification to add some new features in more recent versions of Java. In this tutorial, we are going to discuss the switch case in Java 12. However, before that, let's see an example that shows the implementation of the traditional switch case. FileName: TraditionalSwitch.java Output: The day is not valid. Days of Weekday. Days of Weekend. Using Switch Case of Java 12In Java 12, the switch case has the following modifications:
Using Multiple LabelsFileName: LatestSwitchExpression.java Output: Eleven or Twelve Thirteen or Fourteen The number is invalid. Fifteen or Seventeen or Nineteen The number is invalid. Returning Values Via ArrowWe can also use arrow (->) in our switch expressions. In this case, there is no need of the break statement to prevent the fall-through. The fall-through will not happen in the following case. FileName: LatestSwitchExpression1.java Output: Eleven or Twelve Thirteen or Fourteen The number is invalid. Fifteen or Seventeen or Nineteen The number is invalid. Returning Values Via BreakNow the switch can be treated as an expression, also known as the value breaks. After the break keyword, we can put a value. Observe the following example. FileName: LatestSwitchExpression2.java Output: Eleven or Twelve Thirteen or Fourteen The number is invalid. Fifteen or Seventeen or Nineteen The number is invalid. Note: The above program will not compile with the approach we follow to compile the program that contains the traditional switch expressions. For the compilation process, use the following command.javac --enable-preview --release 12 filename.java After the compilation process, use the following command to run the program. java --enable-preview filename Next TopicThe Pig Game in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India