typestar

Switch expressions in Java

The modern switch returns a value and matches patterns, not just constants.

var code = 404;

// arrow switch returns a value; default keeps it exhaustive
var message = switch (code) {
    case 200 -> "ok";
    case 301, 302 -> "redirected";
    case 404 -> "not found";
    default -> "unhandled " + code;
};
System.out.println(message);

// pattern matching switches on the type
Object value = 3.5;
var kind = switch (value) {
    case Integer n -> "int " + n;
    case Double d -> "double " + d;
    default -> "something else";
};
System.out.println(kind);

How it works

  1. Arrow arms need no break; default keeps the switch exhaustive.
  2. case 301, 302 matches several constants in one arm.
  3. Type patterns like Integer n test and bind in one step.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
455
Tokens
114
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 2 of 3 in Flow control, step 9 of 29 in Language basics.

← Previous Next →

Switch expressions in other languages