java:java12:enhanced-switch
Table of Contents
Java 12 Enhanced Switch
Classic switch (before Java 12)
- ClassicSwitchExample.java
public class ClassicSwitchExample { public static void main(String[] args) { String day = "Monday"; String typeOfDay; switch (day) { case "Monday": typeOfDay = "Start of work week"; break; case "Friday": typeOfDay = "End of work week"; break; case "Saturday": case "Sunday": typeOfDay = "Weekend"; break; default: typeOfDay = "Midweek day"; break; } System.out.println(day + " is a " + typeOfDay); } }
Enhanced switch (starting with Java 12)
- EnhancedSwitchExample.java
public class EnhancedSwitchExample { public static void main(String[] args) { String day = "Monday"; String typeOfDay; typeOfDay = switch (day) { case "Monday" -> "Start of work week"; case "Friday" -> "End of work week"; case "Saturday", "Sunday" -> "Weekend"; default -> "Midweek day"; }; System.out.println(day + " is a " + typeOfDay); } }
- In the enhanced version, the switch is used as an expression, which means it can directly return a value.
- Using the → syntax eliminates the need for the break keyword, as each case is treated as a singular expression, and there's no “fall-through” to the next case.
- In the cases for Saturday and Sunday, we've combined the two cases into one for efficiency and clarity, demonstrating another improvement brought by the modern switch.
java/java12/enhanced-switch.txt · Last modified: 2023/11/29 13:07 by odefta