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
- Arrow arms need no
break;defaultkeeps the switch exhaustive. case 301, 302matches several constants in one arm.- Type patterns like
Integer ntest and bind in one step.
Keywords and builtins used here
casedefaultswitchvar
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.
Step 2 of 3 in Flow control, step 9 of 29 in Language basics.