← Back to Chapters

Java Enhanced Switch

? Java Enhanced Switch

? Quick Overview

The Enhanced Switch Expression in Java simplifies traditional switch statements by allowing concise syntax, arrow labels, and returning values directly.

? Key Concepts

  • Introduced in Java 14 (standard)
  • Uses arrow syntax
  • Can return values
  • No fall-through by default

? Syntax & Theory

Enhanced switch can be used as an expression or statement. It avoids break statements and improves readability.

? View Code Example
// Enhanced switch returning a value
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Invalid day";
};

? Live Output / Explanation

The value of dayName will be Wednesday because the switch expression directly returns the matched result.

? View Code Example
// Printing the result of enhanced switch
System.out.println(dayName);

? Tips & Best Practices

  • Prefer enhanced switch for cleaner logic
  • Use switch expressions when a value is needed
  • Avoid mixing old and new switch styles

? Try It Yourself

  1. Modify the switch to handle months (1–12) and return the month name using enhanced switch.

     

  2. Create a method that takes a 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).

     

  3. Write an enhanced switch that takes a 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.