Contents

Switch Case New JDK Features

Switch Expression (14 Standard / 13 Preview)

Switch expressions can now return a value. And you can use a lambda-style syntax for your expressions, without the fall-through/break issues.

Java 13:

1
2
3
4
5
6
7
boolean result = switch (status) {

    case SUBSCRIBER -> true;
    case FREE_TRIAL -> false;

    default -> throw new IllegalArgumentException("something is murky!");
};

Standardised Switch (with Java 14):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
int numLetters = switch (day) {

    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;

    default -> {
        String s = day.toString();
        int result = s.length();
        yield result;
    }
};

Pattern Matching for switch (17 Preview)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public String test(Object obj) {

    return switch(obj) {

    case Integer i -> "An integer";
    case String s -> "A string";
    case Cat c -> "A Cat";
    
    default -> "I don't know what it is";

    };
}

Now you can pass Objects to switch functions and check for a particular type.