Type patterns in switch
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A type pattern in switch lets a switch choose a branch by the object's type and bind a variable at the same time: case Circle c -> .... It is a standard feature from Java 21, and it replaces long if (x instanceof A a) ... else if (x instanceof B b) chains.
Recap: arrow switch and switch expressions
Since Java 14, a case can use an arrow: case "MON", "WED" -> .... An arrow case runs only its own code. There is no fall-through into the next case, so no break is needed.
Example 1 · Recap: arrow cases and a switch expression
public class ArrowSwitchDemo { static String firstLecture(String day) { return switch (day) { case "MON", "WED", "FRI" -> "9:00 am"; case "TUE", "THU" -> "10:30 am"; case "SAT" -> { String note = "lab only"; yield "11:00 am (" + note + ")"; } default -> "Holiday"; }; }
public static void main(String[] args) { String[] days = {"MON", "THU", "SAT", "SUN"}; for (String d : days) { System.out.println(d + ": " + firstLecture(d)); } }}MON: 9:00 am THU: 10:30 am SAT: 11:00 am (lab only) SUN: Holiday
What this code does
- Each arrow case runs only its own code, so there is no
breakand no accidental fall-through. Several labels can share one arrow. - The
SATcase needs two lines, so it uses a block and gives its value withyield.defaultis required because aStringcan hold any text.
case "SAT", "SUN" -> "Holiday";several labels share one arrow.case "MON" -> { log(); yield "9 am"; }a block gives its value withyield.- Arrow cases never fall through; old
case X:cases do unless you writebreak. - Switch expressions and arrow cases work on Java 17.
A switch expression is a switch that produces a value: String slot = switch (day) { ... };. Each arrow gives the value directly. When a case needs several lines, use a block and give the value with yield. A switch expression must cover every possible input. For a String or an int that means a default case, because the compiler cannot list every value.
Java 21: case Circle c ->
Before Java 21, switch worked only on numbers, characters, strings and enums. Java 21 lets you switch on any reference type, and a case label can be a type pattern.
Example 2 · From an instanceof chain to case Circle c
// Java 21interface Shape { }
record Circle(double radius) implements Shape { }
record Rectangle(double width, double height) implements Shape { }
record Square(double side) implements Shape { }
public class ShapeAreaDemo { static double areaOld(Shape shape) { if (shape instanceof Circle c) { return Math.PI * c.radius() * c.radius(); } else if (shape instanceof Rectangle r) { return r.width() * r.height(); } else if (shape instanceof Square s) { return s.side() * s.side(); } throw new IllegalArgumentException("Unknown shape"); }
static double area(Shape shape) { return switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Rectangle r -> r.width() * r.height(); case Square s -> s.side() * s.side(); default -> throw new IllegalArgumentException("Unknown shape"); }; }
public static void main(String[] args) { Shape[] plots = {new Circle(7), new Rectangle(12, 8.5), new Square(10)}; for (Shape p : plots) { System.out.printf("%s -> old %.2f, new %.2f%n", p, areaOld(p), area(p)); } }}Circle[radius=7.0] -> old 153.94, new 153.94 Rectangle[width=12.0, height=8.5] -> old 102.00, new 102.00 Square[side=10.0] -> old 100.00, new 100.00
What this code does
- Each
caseis a type pattern.case Circle cmatches aCircleand givesc, already typed, soc.radius()works without a cast. The switch is an expression, so it returns the area directly. Shapeis an ordinary interface, so another class could implement it later. That is whydefaultis still required here; it throws for a shape the method does not know.
Example 3 · A switch statement over Object for a report cell
// Java 21import java.time.LocalDate;import java.util.List;
public class ReportCellDemo { static void printCell(Object value) { switch (value) { case Integer i -> System.out.println("count | " + i); case Double d -> System.out.printf("amount | Rs %.2f%n", d); case String s -> System.out.println("text | " + s.toUpperCase()); case LocalDate date -> System.out.println("date | " + date.getDayOfMonth() + "/" + date.getMonthValue()); default -> System.out.println("unknown | " + value.getClass().getSimpleName()); } }
public static void main(String[] args) { List<Object> row = List.of(42, 1299.5, "hostel fee", LocalDate.of(2025, 8, 15), true); for (Object cell : row) { printCell(cell); } }}count | 42 amount | Rs 1299.50 text | HOSTEL FEE date | 15/8 unknown | Boolean
What this code does
- This is a switch statement: each arrow runs code and nothing is returned. A pattern switch statement must still cover every input, so
defaultis needed for anObject. trueis aBoolean, which no case lists, so it reachesdefault. The cases are checked from top to bottom; the first match wins.
case Circle c -> matches when the value is a Circle, and c is that value already cast to Circle.
The cases are tried from top to bottom, and the first one that matches wins. It is the same logic as an if-else chain of instanceof checks, but the shape of the code shows the intent: one value, one branch per type.
Pattern switches work both as expressions (double area = switch (shape) {...};) and as statements. In both forms, Java 21 requires a pattern switch to cover every possible input.
Dominance: broad cases go last
A case dominates a later case when it matches everything the later case would match. case Number n matches every Integer, so a case Integer i after it could never run.
- List the specific types first, such as
case Integer iandcase Long l. - Then the broader parent type, such as
case Number n. - Then
default(orcase Object o) for everything else. - If the compiler says a label is dominated, move that label higher.
Example 4 · Mistake: a broad case before a narrow one
// Java 21public class DominanceErrorDemo { static String kind(Object value) { return switch (value) { case Number n -> "some number"; case Integer i -> "whole number " + i; default -> "not a number"; }; }
public static void main(String[] args) { System.out.println(kind(5)); }}DominanceErrorDemo.java:6: error: this case label is dominated by a preceding case label
case Integer i -> "whole number " + i;
^
1 errorWhat this code does
- Every
Integeris aNumber, socase Number nwould always catch it first andcase Integer icould never run. Java reports this as an error instead of silently ignoring the case. - Fix it by ordering narrow to broad:
case Integer ifirst, thencase Number n, thendefault.
Java treats unreachable cases as mistakes, not as dead code to ignore. The compiler reports "this case label is dominated by a preceding case label". The fix is to order cases from narrow to broad: Integer before Number, Circle before Shape, and the most general type last. The same rule applies to subclasses you write yourself. If PremiumMember extends Member, then case PremiumMember p must come before case Member m.
Find the bug
Find the switch mistake
Each snippet should compile. Tap the line that is wrong, then check the fix.
The selector is an Object, so the switch must cover every value.
Round 1 of 3When default is still needed
A switch over Object, or over an ordinary interface such as Shape, can receive types the compiler has never seen. Another file could add class Hexagon implements Shape tomorrow.
Example 5 · Mistake: no default for an open interface
// Java 21interface Ticket { }
record BusTicket(int fare) implements Ticket { }
record TrainTicket(int fare, String coach) implements Ticket { }
public class MissingDefaultDemo { static int fare(Ticket t) { return switch (t) { case BusTicket b -> b.fare(); case TrainTicket tr -> tr.fare(); }; }
public static void main(String[] args) { System.out.println(fare(new BusTicket(30))); }}MissingDefaultDemo.java:10: error: the switch expression does not cover all possible input values
return switch (t) {
^
1 errorWhat this code does
- Both classes that exist today are listed, but
Ticketis not sealed, so the compiler must assume more classes could implement it. It cannot prove the switch is complete. - Add
default -> throw new IllegalArgumentException("Unknown ticket");, or makeTicketa sealed interface that permits only these two records (next lessons).
So the compiler cannot prove your cases are complete, and you need a default case (or a final catch-all like case Shape s).
Without it, the error is "the switch expression does not cover all possible input values" (or "the switch statement ..."). This is true even when you have listed every class that exists today.
There is one way to drop default: tell the compiler the full list of subtypes with a sealed interface. The Exhaustive switch and case null lesson covers that in full.
Next step
Check your understanding
12 quick questions