Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)
The OCP Java 21 rules for switch: allowed selector types, compile-time constant case values, colon versus arrow labels, fall-through and break, switch expressions with consistent result types, semicolons, yield, exhaustiveness and qualified enum constants.
kvi5hnuCode Sprout team member9 min readOn this page
A long if/else if chain that compares one value against many constants is hard to read and easy to get wrong. switch handles that job in two forms: the switch statement, which runs code, and the switch expression (final since Java 14), which produces a value. This article covers both forms with ordinary constant case values. Article 13 adds pattern matching, when guards and case null, which arrived in Java 21.
Two flavors
String sizeName(int code) { // switch statement
String size;
switch (code) {
case 0:
size = "Small";
break;
case 1:
size = "Medium";
break;
case 2, 3:
size = "Large";
break;
default:
size = "Unknown";
}
return size;
}
String sizeNameBest(int code) { // switch expression
return switch (code) {
case 0 -> "Small";
case 1 -> "Medium";
case 2, 3 -> "Large";
default -> "Unknown";
};
}

Both start with switch and a selector in parentheses, followed by a body in braces containing zero or more case clauses and at most one default. A case can list several values separated by commas. Each clause uses one of two separators:
- Colon (
case 1:): the traditional form, with fall-through. - Arrow (
case 1 ->): no fall-through. The right side is a single expression, a block in braces, or athrowstatement.
One switch can't mix the two separators. A case 0: followed by case 1 -> doesn't compile ("different case kinds used in the switch").
Some syntax rules the exam tests:
- The selector must be in parentheses, and the body must be in braces.
switch (x) {}, with no cases, is legal. - Several values go in one
case, separated by commas:case 1, 2:. Writingcase 1: 2:doesn't compile. defaultneeds its separator:default:ordefault ->.
Which selector types are allowed
Without pattern matching, the selector can be:
int,short,byte,charand their wrappersInteger,Short,Byte,Character(unboxed),String,- an
enumtype, var, when it is inferred as one of these types.
boolean, long, float and double (and their wrappers) are not allowed. This is a classic exam trap. Java 21 also allows any reference type when the case clauses use patterns (article 13), so a Long aLong selector with a case Long l pattern compiles, but a primitive long selector still doesn't, and neither does a constant case 1L:. Primitive patterns that would allow switch on long or boolean are a preview feature in Java 23 through 27 and aren't on either exam.
Acceptable case values
Each case value must be a compile-time constant whose type matches the selector type:
- literals, such as
1,'c'and"Small"; - enum constant names;
- constant variables:
finalvariables of primitive orStringtype initialized with a constant expression, includingstatic finalfields; - constant expressions combining these, such as
3 * 5orMAX + 1.
final int getLimit() { return 4; }
void checkSeats(int seatsTaken) {
final int one = 1;
int two = 2;
final int limit = getLimit();
switch (seatsTaken) {
case one: // OK: a final constant
case two: // DOES NOT COMPILE: not final
case getLimit(): // DOES NOT COMPILE: a method call
case limit: // DOES NOT COMPILE: final, but set at runtime
case 3 * 5: // OK: a constant expression
}
}
The value must also fit the selector's type: case "Ten" with an int selector fails, and so does case 128 with a byte selector. Duplicate values, including the same value written in two different ways, don't compile, and neither do two default clauses.
Enum constants
With an enum selector, the case labels are the enum's constants. Traditionally you write the bare name (case SPRING). Since Java 21 you may also qualify it (case Season.SPRING). In Java 17 that was an error.
enum Season { SPRING, SUMMER, FALL, WINTER }
boolean needsCoat(Season s) {
return switch (s) {
case SPRING, SUMMER -> false;
case Season.FALL, Season.WINTER -> true;
};
}
switch statements
Fall-through and break
With colon labels, the switch jumps to the matching case and then runs every statement below it, through the following case and default labels, until it reaches a break or the end of the switch. This is called fall-through:
switch (level) {
case 1, 2: System.out.print("Easy-");
case 3, 4: System.out.print("Medium-");
default: System.out.print("Custom-");
case 5, 6: System.out.print("Hard-");
case 7, 8: System.out.print("Expert-");
}
For level = 2 this prints Easy-Medium-Custom-Hard-Expert-. For level = 6 it prints Hard-Expert-. For level = 20, control goes to default, which sits in the middle, and falls through from there: Custom-Hard-Expert-.
So in a switch statement, the order of the branches matters, and default doesn't have to come last. Adding break after each branch stops the fall-through. javac -Xlint:fallthrough warns about every fall-through. Whenever you see a colon-form switch on the exam, check every branch for a missing break.
The arrow form in a statement
A switch statement can use arrows too. Each branch then runs alone, with no fall-through and no break needed:
switch (signal) {
case 0 -> System.out.print("Stop");
case 1 -> System.out.print("Go");
default -> System.out.print("Wait");
}
This is still a statement: it produces no value, it isn't assigned to anything, and it doesn't need to cover every possible value. Each arrow branch must be an expression statement (such as a method call or an assignment), a block or a throw. case 1 -> 5; doesn't compile in a statement, because 5 alone isn't a statement.
Scope inside a colon-form switch
The whole body of a colon-form switch is one block. A variable declared in one case is in scope in the cases below it, though it isn't initialized there. In the arrow form, each block has its own scope.
switch expressions
A switch expression produces a value, so it's used where a value is needed: on the right of =, after return, or as a method argument.
var result = switch (status) {
case 404 -> "Not found";
default -> "Other";
};
Semicolons
- Each
casethat produces a value directly (case 404 -> "Not found") ends with a semicolon. - A
caseblock (case 2 -> { ... }) has no semicolon after its closing brace. - The statement that contains the whole expression needs its own semicolon after the final
}.
var drink = switch (cup) {
case 1 -> "Tea" // DOES NOT COMPILE: missing ;
case 2 -> { yield "Coffee"; }; // DOES NOT COMPILE: extra ; after the block
default -> "Water";
} // DOES NOT COMPILE: missing ;
yield
Inside a case block, yield value; provides the result of the switch expression:
int sugar = 12;
var drink = switch (cup) {
case 1 -> "Tea";
case 2 -> { yield "Coffee"; }
case 3 -> {
if (sugar > 10) yield "Syrup";
else yield "Juice";
}
case 4 -> throw new IllegalStateException("retired");
default -> "Water";
};
Every path through a block must either yield a value or throw an exception. A block that can finish without either doesn't compile ("switch rule completes without providing a value"). A return inside a switch expression doesn't compile either ("attempt to return out of a switch expression"), and yield outside a switch expression is an error. yield is a contextual keyword, so int yield = 5; is still a legal variable declaration.
A switch expression can even use colon labels, provided each group ends with yield (case 1: yield "Tea";). That style is rare and allows fall-through, so prefer arrows.
Consistent result types
All branches must produce values that fit the expression's target type:
int floor = 2;
int rooms = switch (floor) {
case 1 -> Integer.valueOf(8); // OK: unboxed
case 2 -> (byte) 6; // OK: widened
default -> 4;
case 4 -> "2"; // DOES NOT COMPILE
case 5 -> 9L; // DOES NOT COMPILE: long to int
case 6 -> null; // DOES NOT COMPILE: null isn't an int
};
With var (or when the expression is passed to a method like println(Object)), the result type is inferred from the branches: an int and a double give a double, and a String and an int give a common reference type.
Exhaustiveness
A switch expression must always produce a value, so it must cover every possible selector value. It's exhaustive if:
- it has a
defaultclause, or - its selector is an enum and every constant has a
case, or - its patterns cover every possible type (article 13).
Integer price = switch (size) { // DOES NOT COMPILE: what if size is "XL"?
case "S" -> 3;
case "M" -> 4;
};
Listing all values doesn't work for int, or even for byte. Only enums (and sealed types, article 13) count. For an enum that is fully covered, default is optional, but it can still be useful: if someone later adds a constant, a default keeps the code compiling, while leaving it out makes the compiler point at every switch that needs updating.
A switch statement with constant labels doesn't need to be exhaustive. Article 13 shows the cases where it must be.
What's current
- Arrow labels,
switchexpressions andyieldhave been final since Java 14. Java 21 added patterns and qualified enum constants incaselabels (articles 13 and 39). - Java 22 finalized unnamed patterns (
case Point(var x, _)). They're on the Java 25 exam, not on 1Z0-830. - A
switchonlong,float,doubleorbooleanis still only a preview (primitive patterns, Java 23 to 25). It doesn't compile on Java 21 or 25 without--enable-preview.
Exam traps from this article
A complete example
public class Solution {
enum Season { SPRING, SUMMER, FALL, WINTER }
static final int BONUS = 9; // a constant: allowed as a case value
// A switch statement with fall-through: no break until the expert levels.
@SuppressWarnings("fallthrough") // the fall-through is the point here
static void printLevels(int level) {
switch (level) {
case 1, 2: System.out.print("Easy-");
case 3, 4: System.out.print("Medium-");
default: System.out.print("Custom-");
case 5, 6: System.out.print("Hard-");
case 7, 8: System.out.print("Expert-"); break;
case BONUS: System.out.print("Bonus-");
}
System.out.println();
}
// The same mapping as a switch expression: exactly one branch runs, no break needed.
static String levelName(int level) {
return switch (level) {
case 1, 2 -> "Easy";
case 3, 4 -> "Medium";
case 5, 6 -> "Hard";
case 7, 8 -> "Expert";
case BONUS -> "Bonus";
default -> "Custom";
};
}
// An enum switch expression that lists every constant needs no default.
static boolean needsCoat(Season s) {
return switch (s) {
case SPRING, SUMMER -> false;
case Season.FALL, Season.WINTER -> true; // qualified names: new in Java 21
};
}
// Case blocks produce their value with yield.
static String drinkName(int cup, int sugar) {
return switch (cup) {
case 1 -> "Tea";
case 2 -> { yield "Coffee"; }
case 3 -> {
if (sugar > 10) yield "Syrup";
else yield "Juice";
}
case 4 -> throw new IllegalArgumentException("cup 4 is retired");
default -> "Water";
};
}
public static void main(String[] args) {
printLevels(2); // falls through all the way to the break
printLevels(6); // starts at Hard
printLevels(20); // default is in the middle, and falls through too
printLevels(9);
System.out.println(levelName(2) + " " + levelName(20) + " " + levelName(9));
System.out.println(needsCoat(Season.SUMMER) + " " + needsCoat(Season.WINTER));
System.out.println(drinkName(2, 0) + " " + drinkName(3, 20) + " " + drinkName(3, 5) + " " + drinkName(9, 0));
try {
drinkName(4, 0);
} catch (IllegalArgumentException e) {
System.out.println("exception: " + e.getMessage());
}
// String switch with an arrow-form statement: no fall-through, no value.
String room = "B2";
switch (room) {
case "A1" -> System.out.println("floor 1");
case "B1", "B2" -> System.out.println("floor 2");
default -> System.out.println("unknown floor");
}
}
}
Output:
Easy-Medium-Custom-Hard-Expert-
Hard-Expert-
Custom-Hard-Expert-
Bonus-
Easy Custom Bonus
false true
Coffee Syrup Juice Water
exception: cup 4 is retired
floor 2
Points to notice:
printLevels(9)jumps straight to the constantBONUS.defaultonly runs for values that match nocase.printLevels(20)starts atdefault, which is in the middle, and falls through until thebreak.needsCoathas nodefaultbut compiles, because all four constants are listed.drinkName(4, 0)throws from an arrow branch, which is allowed even though no value is produced.
Common questions
Should I use switch statements or switch expressions? Prefer switch expressions with arrows whenever you're computing a value. They can't fall through by accident, and the compiler checks that every value is covered. Use statements when each branch only performs actions.
Why isn't long allowed?
Switches on constants compile into jump tables or lookup tables indexed by int. long and floating-point values were never supported, and boolean is better handled by if. Java 21's pattern switch accepts Long with type patterns, but not long constants.
Is default required in a switch statement?
No, not for constant labels. A statement that matches nothing simply does nothing. Pattern-matching switch statements are different, as article 13 explains.
Can I put default anywhere?
Yes. In a colon-form statement its position matters, because of fall-through. In arrow forms and expressions, only one branch runs, so the position doesn't matter for constant labels.
Does a switch on a String use equals?
Yes, it compares strings by content (the compiled code uses hashCode first, then equals). Separately, any switch without a case null throws a NullPointerException when the selector is null, whether it switches on a String, an enum or a wrapper. Article 13 shows case null.
Summary
switchstatements run code, andswitchexpressions produce a value. Eachcaseuses:or->, never both in one switch.- Allowed selectors:
int,short,byte,char, their wrappers,String, enums andvarof those types. With patterns, any reference type. Neverboolean,long,floatordouble. casevalues are compile-time constants that match the selector type, with no duplicates. Since Java 21, enum constants may be qualified.- Colon-form statements fall through until
break. Arrow branches never fall through. - Switch expressions need semicolons after value branches and after the whole expression,
yieldin blocks, consistent result types and exhaustiveness (defaultor every enum constant).
Practice quiz
Test yourself with the switch statements and expressions quiz: 10 exam-style questions with explanations.
Previous: Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)
Next: Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)
Related reading
- Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
- Java Pattern Matching: switch Patterns, Record Patterns and Guards

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.