[Java] [Java] Let’s take a look at JDK 13 Switch Expressions (Preview)

1 minute read

5 key features of OpenJDK 13

350: Dynamic CDS Archives 351: ZGC: Uncommit Unused Memory 353: Reimplement the Legacy Socket API 354: Switch Expressions (Preview) 355: Text Blocks (Preview)

Among the above, today I would like to look at “Switch Expressions (Preview)”.

Switch Expressions (Preview)

  • Was it Preview in JDK 12 or 13? Since it is a Preview, it seems that it cannot be used unless the option of –enable-preview is given.

・Arrow labels


static void howMany(int k) {
    switch (k) {
        case 1 -> System.out.println("one");
        case 2 -> System.out.println("two");
        default -> System.out.println("many");
    }
}

I used to use “case L:” often, but now I can also use it like “case L->”. However, if you write it like “case L->”, you don’t need to write break because there is no full through.

When calling, it is as follows.

howMany(1);
howMany(2);
howMany(3);
result

one
two
many

・Switch expressions

switch can be used in expression.


static void howMany(int k) {
    System.out.println(
        switch (k) {
            case 1 -> "one"
            case 2 -> "two"
            default -> "many"
        }
    );
}

Therefore, you can assign the result of the switch statement to a variable.


T result = switch (arg) {
    case L1 -> e1;
    case L2 -> e2;
    default -> e3;
};

・Yielding a value

The “yield” keyword was added.


int j = switch (day) {
    case MONDAY -> 0;
    case TUESDAY -> 1;
    default -> {
        int k = day.toString().length();
        int result = f(k);
        yield result; // set return value of switch statement
    }
};

“Yield” can be used in the switch statement of “case L:” expressions.


int result = switch (s) {
    case "Foo":
        yield 1;
    case "Bar":
        yield 2;
    default:
        System.out.println("Neither Foo nor Bar, hmmm...");
        yield 0;
};

Reference

  • https://openjdk.java.net/projects/jdk/13/
  • https://openjdk.java.net/jeps/354
  • https://johngrib.github.io/wiki/jdk13/