Switch expressions
Since Java 14, switch can be an expression that produces a value, and cases can use an arrow that never falls through. Together they remove the two classic switch bugs, a forgotten break and a variable left unassigned in some case. Every example was run on JDK 25, including the bytecode javac produces for number, String and enum switches.
Contents
Introduction
Java has had a switchbreak
Java 14 added two separate features that fix them:
- Arrow cases,
, run only the code to the right of the arrow and never fall through. Several labels share a case when they are separated by commas.case 6, 7 -> ... - Switch expressions produce a value, so they can appear on the right of
, as an argument or after= . An expression must be exhaustive, which means some case must apply to every possible value, so the result is always defined.return
The two are independent. An arrow switch can be a statement, and an expression can use colon cases with yield
| Feature | Since | Best for |
|---|---|---|
intcharshortbyte | Java 1.0 | Numeric codes |
| Enum selectors | Java 5 | States, kinds, modes |
String | Java 7 | Commands, keys, text codes |
| Arrow cases and switch expressions | Java 14, after previews in 12 and 13 | Computing a value with no fall-through |
Patterns, case null | Java 21 | Branching on type, see |
In the Java 12 preview, a switch expression returned its value with break valueyield
Arrow cases and the fall-through bug
Here is the classic bug. The weekend case is missing its breakcase 1
public class FallThroughBug {
@SuppressWarnings("fallthrough") // the fall-through is the bug being shown
static String kind(int day) {
String kind = "unknown";
switch (day) {
case 6:
case 7:
kind = "weekend";
// missing break: execution continues into case 1
case 1:
kind = "start of week";
break;
default:
kind = "weekday";
}
return kind;
}
public static void main(String[] args) {
System.out.println("day 1: " + kind(1) + ", day 3: " + kind(3) + ", day 6: " + kind(6));
}
}
Running it prints:
day 1: start of week, day 3: weekday, day 6: start of week
Day 6 came out as "start of week". The code set kindcase 1break-Xlint:fallthrough@SuppressWarnings
The same logic as an arrow switch expression cannot fall through:
public class ArrowSwitch {
static String kind(int day) {
return switch (day) {
case 6, 7 -> "weekend"; // several labels share one case
case 1 -> "start of week";
case 2, 3, 4, 5 -> "weekday";
default -> throw new IllegalArgumentException("day " + day);
};
}
public static void main(String[] args) {
System.out.println("day 1: " + kind(1) + ", day 3: " + kind(3) + ", day 6: " + kind(6));
try {
kind(9);
} catch (IllegalArgumentException e) {
System.out.println("kind(9) threw: " + e.getMessage());
}
}
}
Running it prints:
day 1: start of week, day 3: weekday, day 6: weekend
kind(9) threw: day 9
Day 6 is now "weekend". The second line shows that a case may throw instead of producing a value, even in an expression, so kind(9)
Blocks, yield and exhaustive enum switches
What if a case needs more than one expression? Put a block on the right of the arrow and end it with yield valueyieldreturnreturn
public enum Size { SMALL, MEDIUM, LARGE }
Members get 50 cents off a medium and 10% off a large, so each size follows a different rule:
public class YieldBlocks {
static int priceCents(Size size, boolean member) {
return switch (size) {
case SMALL -> 250;
case MEDIUM -> {
int base = 350;
yield member ? base - 50 : base; // yield gives the block's value
}
case LARGE -> {
int base = 450;
yield member ? base - base / 10 : base;
}
}; // all three sizes listed: no default
}
public static void main(String[] args) {
for (Size s : Size.values()) {
System.out.println(s + ": regular " + priceCents(s, false)
+ ", member " + priceCents(s, true));
}
}
}
Running it prints:
SMALL: regular 250, member 250
MEDIUM: regular 350, member 300
LARGE: regular 450, member 405
Small has no member discount, medium is 350 - 50 = 300 cents, and large is 450 - 45 = 405. The switch lists all three sizes and has no defaultpriceCents
yield
public class ColonYield {
static String status(int code) {
return switch (code) {
case 200:
yield "OK";
case 301:
case 302: // 301 falls through to here
yield "redirect";
default:
yield "other";
};
}
public static void main(String[] args) {
System.out.println(status(200) + ", " + status(301) + ", " + status(404));
}
}
Running it prints:
OK, redirect, other
Every path ends with yieldcase 301, 302 ->
Switching on strings
String switches work naturally with arrows. The next example is a tiny interpreter that applies commands to a running value. Each command is a record in its own file:
// One step of a tiny program: a command name and its number
public record Command(String name, int arg) {
}
The command timesmuljumpdefault
import java.util.List;
public class StringSwitch {
static int apply(int value, Command c) {
return switch (c.name()) {
case "add" -> value + c.arg();
case "sub" -> value - c.arg();
case "mul", "times" -> value * c.arg();
case "reset" -> 0;
default -> {
System.out.println(" ignoring unknown command '" + c.name() + "'");
yield value;
}
};
}
public static void main(String[] args) {
List<Command> program = List.of(new Command("add", 5), new Command("times", 3),
new Command("jump", 1), new Command("sub", 4));
int value = 0;
for (Command c : program) {
value = apply(value, c);
System.out.println(c.name() + " " + c.arg() + " -> " + value);
}
}
}
Running it prints:
add 5 -> 5
times 3 -> 15
ignoring unknown command 'jump'
jump 1 -> 15
sub 4 -> 11
The value goes 0 + 5 = 5, then 5 × 3 = 15, stays 15 for the unknown command and ends at 15 - 4 = 11. String cases are compared with equalss.toLowerCase(Locale.ROOT)nullNullPointerExceptioncase null
How javac compiles a switch
A switch expression compiles to the same bytecode as a switch statement. What does that bytecode look like? Start with two switches over numbers, one with close values and one with values far apart:
public class NumberSwitches {
static int dense(int n) {
return switch (n) {
case 1 -> 10;
case 2 -> 20;
case 3 -> 30;
default -> 0;
};
}
static int sparse(int n) {
return switch (n) {
case 1 -> 10;
case 1000 -> 20;
case 50000 -> 30;
default -> 0;
};
}
}
Compiling it and running javap -c -p NumberSwitches
static int dense(int);
Code:
0: iload_0
1: tableswitch { // 1 to 3
1: 28
2: 33
3: 38
default: 43
}
28: bipush 10
30: goto 44
33: bipush 20
35: goto 44
38: bipush 30
40: goto 44
43: iconst_0
44: ireturn
static int sparse(int);
Code:
0: iload_0
1: lookupswitch { // 3
1: 36
1000: 41
50000: 46
default: 51
}
36: bipush 10
38: goto 52
41: bipush 20
43: goto 52
46: bipush 30
48: goto 52
51: iconst_0
52: ireturn
The cases 1, 2 and 3 in densetableswitchsparselookupswitch
A string switch is more interesting. This one uses two strings with the same hash code:
public class TextSwitch {
static int text(String s) {
return switch (s) { // "Aa" and "BB" have the same hashCode(), 2112
case "Aa" -> 1;
case "BB" -> 2;
default -> 0;
};
}
}
Its bytecode:
static int text(java.lang.String);
Code:
0: aload_0
1: astore_1
2: iconst_m1
3: istore_2
4: aload_1
5: invokevirtual #7 // Method java/lang/String.hashCode:()I
8: lookupswitch { // 1
2112: 28
default: 53
}
28: aload_1
29: ldc #13 // String BB
31: invokevirtual #15 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
34: ifeq 42
37: iconst_1
38: istore_2
39: goto 53
42: aload_1
43: ldc #19 // String Aa
45: invokevirtual #15 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
48: ifeq 53
51: iconst_0
52: istore_2
53: iload_2
54: lookupswitch { // 2
0: 80
1: 84
default: 88
}
80: iconst_1
81: goto 89
84: iconst_2
85: goto 89
88: iconst_0
89: ireturn
It runs in three steps, as the picture shows:
At instruction 5 the code calls hashCode()lookupswitchequalslookupswitchequals
Last, an enum switch. The enum is in its own file:
public enum Color { RED, GREEN, BLUE }
public class ColorSwitch {
static int color(Color c) {
return switch (c) {
case RED -> 1;
case GREEN -> 2;
case BLUE -> 3;
};
}
}
Its bytecode:
static int color(Color);
Code:
0: getstatic #7 // Field ColorSwitch$1.$SwitchMap$Color:[I
3: aload_0
4: invokevirtual #13 // Method Color.ordinal:()I
7: iaload
8: tableswitch { // 1 to 3
1: 46
2: 50
3: 54
default: 36
}
36: new #19 // class java/lang/MatchException
39: dup
40: aconst_null
41: aconst_null
42: invokespecial #21 // Method java/lang/MatchException."<init>":(Ljava/lang/String;Ljava/lang/Throwable;)V
45: athrow
46: iconst_1
47: goto 55
50: iconst_2
51: goto 55
54: iconst_3
55: ireturn
The code reads ColorSwitch$1.$SwitchMap$Colorordinal()ColordefaultMatchException
The type of a switch expression, and an unboxing trap
A switch expression has a type, worked out from its arms, much like the conditional operator ? :
public class ArmTypes {
public static void main(String[] args) {
int k = 1; // the first arm is always taken
var a = switch (k) {
case 1 -> 1; // int
default -> 2.5; // double
};
var b = switch (k) {
case 1 -> 42; // Integer
default -> "none"; // String
};
long c = switch (k) {
case 1 -> 7; // each arm converted to long
default -> 8L;
};
System.out.println("int and double arms: " + a);
System.out.println("Integer and String arms: " + b + ", a " + b.getClass().getSimpleName());
System.out.println("assigned to long: " + c);
}
}
Running it prints:
int and double arms: 1.0
Integer and String arms: 42, a Integer
assigned to long: 7
With intdoubledouble? :IntegerStringvarIntegerlong
One combination throws. Here an arm returns an Integerint
import java.util.Map;
public class UnboxingTrap {
public static void main(String[] args) {
Map<String, Integer> stock = Map.of("tea", 3); // no "milk" in stock
int count = switch ("milk") {
case "tea", "milk" -> stock.get("milk"); // a null Integer
default -> 0;
};
System.out.println("count " + count);
}
}
Running it prints:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
at UnboxingTrap.main(UnboxingTrap.java:7)
stock.get("milk")nullintNullPointerExceptionMap.getgetOrDefaultInteger
Last, the selector itself. Is it evaluated once, or once per case?
public class SelectorOnce {
static int calls = 0;
static int next() {
return ++calls;
}
public static void main(String[] args) {
String r = switch (next()) {
case 1 -> "one";
case 2 -> "two";
default -> "many";
};
System.out.println("selector evaluated " + calls + " time, result " + r);
}
}
Running it prints:
selector evaluated 1 time, result one
The selector ran exactly once, before any case was compared, so a selector with side effects is safe.
What the compiler checks
Which mistakes does the compiler catch? Each row below is one method body, compiled with javac 25. It switches on a three-constant enum, SizeSML
class T {
int n;
void m(Size s) {
// the body from the table goes here
}
}
| What the code does | Body | javac says |
|---|---|---|
| A statement that skips a constant | switch (s) { case S -> n = 1; case M -> n = 2; } | compiles |
| An expression that skips a constant | n = switch (s) { case S -> 1; case M -> 2; }; | the switch expression does not cover all possible input values |
A statement that assigns x | int x; switch (s) { case S -> x = 1; case M -> x = 2; case L -> x = 3; } n = x; | variable x might not have been initialized |
| The same with an expression | int x = switch (s) { case S -> 1; case M -> 2; case L -> 3; }; n = x; | compiles |
A block that ends without yield | n = switch (s) { case S -> 1; case M -> 2; case L -> { n++; } }; | switch rule completes without providing a value |
return | n = switch (s) { case S -> 1; case M -> 2; case L -> { return; } }; | attempt to return out of a switch expression |
| The same label twice | n = switch (s) { case S -> 1; case M, S -> 2; case L -> 3; }; | duplicate case label |
| Arrow and colon cases in one switch | n = switch (s) { case S -> 1; case M: yield 2; default -> 3; }; | different case kinds used in the switch |
The first four rows show why expressions are safer. A statement may skip a constant, while the same cases as an expression are rejected, because the result would be undefined for Lx
The other rows are about how an expression ends. Every arm must give a value or throw, and returnbreakcontinue
Which form to use
Colon cases case X: | Arrow cases case X -> | |
|---|---|---|
| Falls through | Yes, until break | Never |
| Several labels | case 1: case 2:case 1, 2: | case 1, 2 -> |
| As a statement | Not checked for exhaustiveness (without patterns) | Not checked for exhaustiveness (without patterns) |
| As an expression | Every path ends with yield | An expression, a block with yieldthrow |
- To compute a value from a selector, use an arrow switch expression.
- To run different side effects per case, use an arrow switch statement.
- Over an enum, use an expression without
, so a new constant causes a compile error instead of a silent default.default - Deliberate fall-through is rarely clearer than a comma list, so keep colon cases for old code.
- To branch on the type of an object, use
pattern matching for switch (Java 21).