java:java12:enhanced-switch
This is an old revision of the document!
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); } }
java/java12/enhanced-switch.1701255864.txt.gz · Last modified: 2023/11/29 13:04 by odefta