Patterns in switch
Combine sealed types and patterns.
Patterns in switch is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Patterns in switch
Switch has grown from matching constants to matching patterns. Combined with sealed types and records, a switch can dispatch on type, destructure data, and guarantee completeness.
Type Patterns in switch
Each case can be a type pattern, binding a typed variable for that branch.
public class Main {
static String kind(Object o) {
return switch (o) {
case Integer i -> "int " + i;
case String s -> "string " + s;
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(kind(42));
System.out.println(kind("hi"));
System.out.println(kind(3.14));
}
}Sealed Types Need No default
When the selector is a sealed type and you cover every permitted subtype, the switch is exhaustive without a default.
public class Main {
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double s) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.r() * c.r();
case Square sq -> sq.s() * sq.s();
};
}
public static void main(String[] args) {
System.out.printf("%.2f%n", area(new Square(3)));
}
}Record Patterns in Cases
Cases can destructure records, exposing components directly to the branch body.
public class Main {
sealed interface Shape permits Circle, Rectangle {}
record Circle(double r) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Rectangle(double w, double h) -> w * h;
};
}
public static void main(String[] args) {
System.out.printf("%.2f%n", area(new Rectangle(2, 5)));
}
}Guards with when
A when clause adds a boolean guard to a case. The case matches only if the pattern fits and the guard is true.
public class Main {
static String size(Object o) {
return switch (o) {
case Integer i when i < 0 -> "negative";
case Integer i when i == 0 -> "zero";
case Integer i -> "positive";
default -> "not an int";
};
}
public static void main(String[] args) {
System.out.println(size(-5));
System.out.println(size(0));
System.out.println(size(7));
}
}Order Matters With Guards
Guarded cases are tried top to bottom. A more specific guarded case must come before a broader unguarded case, or the broad one would swallow it.
Handling null
Add case null to handle a null selector; otherwise the switch throws NullPointerException. You can even combine it as case null, default.
public class Main {
static String label(String s) {
return switch (s) {
case null -> "missing";
case "yes" -> "affirmative";
default -> "other: " + s;
};
}
public static void main(String[] args) {
System.out.println(label(null));
System.out.println(label("yes"));
System.out.println(label("maybe"));
}
}Nested Patterns in switch
Cases can nest record patterns to match deep structures and guard on inner values in one place.
public class Main {
record Point(int x, int y) {}
record Line(Point a, Point b) {}
static String describe(Object o) {
return switch (o) {
case Line(Point(var x1, var y1), Point(var x2, var y2)) when x1 == x2 -> "vertical";
case Line(Point a, Point b) -> "line";
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(describe(new Line(new Point(1, 0), new Point(1, 5))));
System.out.println(describe(new Line(new Point(0, 0), new Point(2, 3))));
}
}Statements and Expressions
Pattern switch works both as an expression (yielding a value with -> or yield) and as a statement. The exhaustiveness rules apply when the selector is sealed.
Replacing Visitor Code
Together, sealed types plus pattern switch replace verbose visitor patterns and instanceof ladders with concise, compiler-checked dispatch over a closed model.
A Complete Interpreter
An expression evaluator using a sealed model and a pattern switch.
public class Main {
sealed interface Expr permits Num, Add, Mul {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
static int eval(Expr e) {
return switch (e) {
case Num(int v) -> v;
case Add(Expr l, Expr r) -> eval(l) + eval(r);
case Mul(Expr l, Expr r) -> eval(l) * eval(r);
};
}
public static void main(String[] args) {
Expr e = new Add(new Num(2), new Mul(new Num(3), new Num(4)));
System.out.println(eval(e));
}
}Quick Check
Test your understanding of patterns in switch.
Recap
You learned patterns in switch.
- Cases can be type patterns and record patterns, with destructuring.
- Sealed selectors give exhaustive switches without
default. whenguards refine cases; order matters.case nullhandles null safely.
Frequently asked questions
Is the “Patterns in switch” lesson free?
Yes — the full text of “Patterns in switch” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Patterns in switch”?
Combine sealed types and patterns. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Patterns in switch” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Pattern Matching for instanceof
- Record Patterns
- Nested Record Patterns
- Patterns in switch