Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
Choose among many values with Java's switch expression: the arrow syntax, selector types, several labels per case, enums without prefixes, exhaustiveness and default, blocks with yield, throwing from a case, and handling null with case null.
kvi5hnuCode Sprout team member7 min readOn this page
The conditional operator ?: chooses between two values. When you need to choose among many, Java (since version 14) has the switch expression. It takes a value, compares it against a list of cases, and produces the result of the matching case:
String zone = switch (ring) {
case 0 -> "Core";
case 1 -> "Inner";
case 2 -> "Middle";
case 3 -> "Outer";
default -> "???";
};

Like every expression, a switch expression has a value, here a String that's assigned to zone. Note the semicolon after the closing brace: it ends the assignment statement.
Anatomy
| Part | Name | Notes |
|---|---|---|
switch (ring) | the selector expression | Its value is the selector |
case 0 -> "Core"; | a case with a label (0) and a result | The arrow -> separates the label from the result |
default -> "???"; | the default case | Used when no label matches |
Exactly one case is chosen, and its result becomes the value of the whole expression. There's no fall-through and no break: the problems of C's switch statement don't exist in this form.
What Can You Switch On?
For now, the selector can be:
- an integral type:
int,short,byte,char(and their wrapper classes), - a
String, - an enum constant.
You can't switch on long, float, double or boolean with constant labels. Pattern matching (Java 21) extends switch to any object type, as you'll see later.
Each label must be a compile-time constant of a matching type: a literal like 2 or "Middle", a final constant, or an enum constant. Variables can't be labels, and two cases can't have the same label.
Several Labels per Case
Separate labels with commas when several values produce the same result:
int fee = switch (zone) {
case "Core", "Inner", "Outer" -> 5;
case "Middle" -> 3;
default -> -1;
};
String labels are compared with equals, so case matters: "middle" doesn't match "Middle".
Enums: No Prefix Needed
When the selector is an enum, write the bare constant names. The compiler knows which enum they belong to:
enum Tier { BASIC, SILVER, GOLD, PLATINUM }
Tier memberTier = Tier.PLATINUM;
String label = switch (memberTier) {
case BASIC -> "B"; // not Tier.BASIC
case SILVER -> "S";
case GOLD -> "G";
case PLATINUM -> "P";
};
This switch has no default, and that's fine, because every constant of Tier is covered.
Exhaustiveness: Every Value Must Be Handled
A switch expression must always produce a value, so the compiler insists that the cases cover every possible selector value. This property is called exhaustiveness:
- With an
int,charorStringselector, you can't list every possible value, so adefaultis required. - With an enum, you need either a case for every constant or a
default.
Leaving it out is a compile error:
int code = 7;
String name = switch (code) {
case 0 -> "Core";
case 1 -> "Inner";
};
error: the switch expression does not cover all possible input values
Blocks and yield
Usually a case's result is a single expression. If you need several statements to compute it, use a block in braces and deliver the value with yield:
public class Solution {
enum Tier { BASIC, SILVER, GOLD, PLATINUM }
public static void main(String[] args) {
int ring = 2;
String zone = switch (ring) {
case 0 -> "Core";
case 1 -> "Inner";
case 2 -> "Middle";
case 3 -> "Outer";
default -> "???";
};
System.out.println(zone);
int fee = switch (zone) {
case "Core", "Inner", "Outer" -> 5;
case "Middle" -> 3;
default -> -1;
};
System.out.println(fee);
Tier memberTier = Tier.PLATINUM;
String label = switch (memberTier) {
case BASIC -> "B";
case SILVER -> "S";
case GOLD -> "G";
case PLATINUM -> "P";
};
System.out.println(label);
char grade = 'B';
int points = switch (grade) {
case 'A' -> 4;
case 'B' -> 3;
case 'C' -> 2;
default -> {
System.out.println("Unusual grade: " + grade);
yield 0;
}
};
System.out.println(points);
Tier missing = null;
String safe = switch (missing) {
case BASIC, SILVER -> "standard";
case GOLD, PLATINUM -> "premium";
case null -> "not set";
};
System.out.println(safe);
}
}
Middle
3
P
3
not set
yield is like return, but for a switch expression: it ends the block and supplies the value. (return isn't allowed there, because it would exit the whole method.)
A more realistic use of a block, computing the number of days in a month:
int days = switch (month) {
case 4, 6, 9, 11 -> 30;
case 2 -> {
boolean leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
yield leap ? 29 : 28;
}
default -> 31;
};
Throwing an Exception from a Case
If a value is invalid, a case can throw an exception instead of producing a value:
String kind = switch (day) {
case 1, 2, 3, 4, 5 -> "weekday";
case 6, 7 -> "weekend";
default -> throw new IllegalArgumentException("Bad day: " + day);
};
This is the clean way to handle "can't happen" values: the program stops loudly instead of continuing with a made-up value like "???". Exceptions get a full part of this course.
null Selectors and case null
If the selector is a reference type (String, an enum, a wrapper) and its value is null, a switch without special handling throws a NullPointerException:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Solution$Tier.ordinal()" because "<local1>" is null
Since Java 21 you can handle null explicitly with case null, as in the missing example above. Note:
defaultdoes not matchnull. A switch withdefaultbut nocase nullstill throws onnull.- To treat
nulllike everything else unmatched, combine them:case null, default -> ….
String action = switch (command) {
case "start", "run" -> "Starting";
case "stop" -> "Stopping";
case null, default -> "Unknown command";
};
Switch Expression vs ?: vs if
| Need | Best tool |
|---|---|
| Choose between two values | condition ? a : b |
| Choose among many values by matching one selector against constants | switch expression |
Conditions that aren't simple equality (x > 100, several variables) | if / else if (or switch with patterns and guards, covered later) |
| Run different statements rather than compute a value | if statements or a switch statement |
Common questions
Can I switch on a long, double or boolean?
Not in final Java (as of Java 27). Primitive patterns, a preview feature since Java 23 (article 52), extend switch to all primitive types; on Java 25 you can try them with --enable-preview. Until that becomes final, use if/else chains for long, double and boolean values.
Can a case label be a range, like case 1..5?
No, Java has no range labels. List the values (case 1, 2, 3, 4, 5 ->), or use a pattern switch with a guard: case Integer n when n >= 1 && n <= 5 ->. For wide ranges, an if/else chain is usually clearer.
Do I need break in an arrow-form switch?
No. Arrow cases never fall through, so a break is unnecessary. In a switch expression it is even a compile error, because each case must produce a value with an expression, yield or throw.
What happens if an enum gets a new constant after my code was compiled?
If the switch expression covered every constant without a default, the compiler adds a hidden default that throws MatchException (IncompatibleClassChangeError before Java 21) when it meets the unknown constant at runtime. Recompiling turns that into a compile error that points you to each switch you need to update.
Is a switch faster than an if/else chain?
Often slightly, because the compiler can use a jump table (tableswitch) or a binary search (lookupswitch) for integer labels, and hash codes for strings. For a handful of cases the difference is negligible. Pick switch for readability and for the exhaustiveness check.
Summary
- A switch expression selects one value among many:
var result = switch (selector) { case A -> x; … default -> y; };. - Arrow cases (
->) never fall through and need nobreak; exactly one case runs. - Selectors (for now): integral types,
String, enums. Labels must be compile-time constants; several labels can share a case:case 1, 2, 3 ->. - Enum labels are written without the enum name.
- Switch expressions must be exhaustive:
defaultis required forint/char/Stringselectors; for enums, either cover every constant or adddefault. - Use a block with
yieldfor multi-statement cases; a case may alsothrow. - A
nullselector throwsNullPointerExceptionunless there is acase null(Java 21).defaultdoesn't matchnull; usecase null, default.
Practice Questions
Write a switch expression that maps an int month (1–12) to its quarter "Q1"–"Q4", and throws an exception for other values.
String quarter = switch (month) {
case 1, 2, 3 -> "Q1";
case 4, 5, 6 -> "Q2";
case 7, 8, 9 -> "Q3";
case 10, 11, 12 -> "Q4";
default -> throw new IllegalArgumentException("Invalid month: " + month);
};
An enum Light { RED, YELLOW, GREEN } is switched on with cases for RED and GREEN only, and no default. What happens?
Compile error: the switch expression doesn't cover all possible input values. Add a case for YELLOW (recommended) or a default.
Why must a switch expression with a String selector always have a default?
There are infinitely many possible strings, so the listed labels can never cover them all. Without default, some selector value would have no result, which isn't allowed for an expression.
In a switch expression case block, why use yield instead of return?
return would exit the entire enclosing method. yield exits only the switch case and provides the value of the switch expression.
A switch over a String has default -> "other". Is it safe if the string is null?
No. default doesn't match null, so the switch throws a NullPointerException. Use case null, default -> "other" (Java 21+), or check for null before the switch.
Previous: Java Operators: Increment, Relational, Logical, Conditional, Bitwise and Precedence
Next: Java Strings: Concatenation, Substrings, Immutability and Comparing with equals
Related reading
- Java Variables, Constants, var and final Explained
- Java Operators: Increment, Relational, Logical, Conditional, Bitwise and Precedence
- Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
- Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
- Java Keywords Reference: Every Keyword, Contextual Keyword and Literal

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.