The Enhanced Switch Expression in Java simplifies traditional switch statements by allowing concise syntax, arrow labels, and returning values directly.
Enhanced switch can be used as an expression or statement. It avoids break statements and improves readability.
// Enhanced switch returning a value
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Invalid day";
};
The value of dayName will be Wednesday because the switch expression directly returns the matched result.
// Printing the result of enhanced switch
System.out.println(dayName);
char grade ('A', 'B', 'C', 'D', 'F') and uses an enhanced switch expression to return the corresponding GPA point (4.0, 3.0, 2.0, 1.0, 0.0).
String for the day of the week. Return "Work Mode" for Monday through Friday, and "Party Mode" for Saturday and Sunday. Use comma-separated labels to group the days.