Java 17 Switch Statement: Pattern Matching and Expression Support

2 min read

Java 17 Switch Statement: Pattern Matching and Expression Support

Java 17 continues to evolve the language’s syntax, making code more concise and expressive. One of the key improvements is the enhancement of the switch statement. Java 17 introduced pattern matching for switch and enhanced switch expressions, making it more powerful and safer.

What’s New in Java 17 switch?

Java 17 brings several enhancements:

  • Switch as an Expression: You can use switch to return values.
  • Arrow (->) Syntax: Cleaner, concise syntax.
  • Multiple Labels: Group cases easily.
  • Exhaustiveness: Ensures all enum/sealed types are handled.
  • Pattern Matching (Preview feature in Java 17): Type-check and cast in one go.

Syntax Comparison

Traditional switch (Pre-Java 12)

switch (day) {
    case MONDAY:
    case TUESDAY:
    case WEDNESDAY:
        System.out.println("Weekday");
        break;
    case SATURDAY:
    case SUNDAY:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Invalid day");
}

Enhanced switch Expression (Java 17)

String result = switch (day) {
    case MONDAY, TUESDAY, WEDNESDAY -> "Weekday";
    case SATURDAY, SUNDAY -> "Weekend";
    default -> throw new IllegalArgumentException("Invalid day");
};

Full Example with Java 17 Features

public class SwitchExample {

    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }

    public static void main(String[] args) {
        Day day = Day.SATURDAY;
        String message = getDayType(day);
        System.out.println("Today is: " + message);

        Object obj = 123;
        String type = getType(obj);
        System.out.println("Type is: " + type);
    }

    // Using switch as an expression with multiple labels
    static String getDayType(Day day) {
        return switch (day) {
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
            case SATURDAY, SUNDAY -> "Weekend";
        };
    }

    // Pattern matching in switch (preview feature, enable with --enable-preview)
    static String getType(Object obj) {
        return switch (obj) {
            case String s -> "String of length " + s.length();
            case Integer i -> "Integer value " + i;
            case Double d -> "Double value " + d;
            case null -> "Null value";
            default -> "Unknown type";
        };
    }
}

Notes on Pattern Matching

Pattern matching for switch is still a preview feature in Java 17. To use it:

  • Compile with: bashCopyEditjavac --enable-preview --release 17 SwitchExample.java
  • Run with: bashCopyEditjava --enable-preview SwitchExample

Benefits of Java 17 switch

  • Less boilerplate: No need for break.
  • Safer: Exhaustiveness checks for sealed types/enums.
  • More expressive: Handle logic by value and type in a cleaner way.
  • Pattern matching: Cleaner type checks and casts.

Conclusion

The Java 17 switch statement is a major step forward in making Java more expressive and developer-friendly. Whether you’re checking enum values, returning results, or performing pattern matching, the new switch reduces code clutter and enhances safety.

If you’re moving from older versions of Java, learning this modern syntax is well worth your time.

🤞 Never miss a story from us, get weekly updates to your inbox!

Leave a Reply

Your email address will not be published. Required fields are marked *