How do I use switch expressions introduced in Java 14+?

The switch expression, introduced in Java 12 (as a preview feature) and became a standard feature in Java 14, provides a more concise and powerful way to use switch statements. Here’s how to use it effectively:

Key Features of Switch Expressions

  1. Simpler Syntax: The new syntax allows the use of the -> syntax to eliminate fall-through behavior.
  2. Expression Form: The switch can now return a value directly.
  3. Multiple Labels: Multiple case labels can share the same logic using a comma-separated list.
  4. No More Breaks: No need for the break keyword after each case.

Syntax for Switch Expressions

Here’s a quick breakdown:

String dayType = switch (dayOfWeek) {
    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday";
    case "Saturday", "Sunday" -> "Weekend";
    default -> throw new IllegalArgumentException("Invalid day: " + dayOfWeek);
};

Explanation:

  • The -> syntax replaces the colon and break of the traditional switch.
  • default acts as a fallback for unmatched cases.
  • The result of the switch is assigned directly to the variable dayType.
  • Multiple cases separated by commas handle identical conditions.

Examples of Switch Expressions

Return a Value Directly from switch

int month = 3;
int daysInMonth = switch (month) {
    case 1, 3, 5, 7, 8, 10, 12 -> 31;
    case 4, 6, 9, 11 -> 30;
    case 2 -> 28; // Use 29 for leap years, this is simplified.
    default -> throw new IllegalArgumentException("Invalid month: " + month);
};
System.out.println("Days in Month: " + daysInMonth);

Using Code Blocks in a Case

For more complex logic, you can use curly braces {} to group multiple statements into a block. In such cases, you must use the yield keyword to specify a value to be returned.

String grade = "B";
String feedback = switch (grade) {
    case "A", "B" -> "Great job!";
    case "C", "D" -> {
        System.out.println("Encouraging message for grade: " + grade);
        yield "Needs improvement.";
    }
    case "F" -> "Failed.";
    default -> throw new IllegalArgumentException("Unknown grade: " + grade);
};
System.out.println("Feedback: " + feedback);

Advantages Over Traditional switch

  1. No Fall-Through: Avoid accidentally executing multiple cases (common bug with traditional switch).
  2. Cleaner Syntax: Easier to read and write due to the arrow operator (->) and elimination of break.
  3. Enhanced Type Safety: The returned value must match the expected type assigned to the variable.
  4. Pattern Matching (Java 17+): Future extensions allow switch with pattern matching for richer capabilities.

Use Cases

  1. Assigning values directly with clear logic.
  2. Simplifying code structure for multiple conditions or enums.
  3. Handling complex branching logic.