Command Palette

Search for a command to run...

Back to the lesson: Topic 11.2 — Pattern Matching for switch
Core Java · Example 2 of 4 Java 21+

Exhaustive switch over a sealed interface

Delete the case Square q line in area() and compile: the error lists the switch, not a runtime bug.

From Java 21, switch can test the type and shape of any object, not only constants: case Circle c -> ..., with when guards, case null, and a compiler that checks every possible type is handled. With sealed types it replaces long if/instanceof chains with one exhaustive, checked expression.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static String classify(Object o) that returns "null", "even N"/"odd N" for Integers, "empty text" or "text 'S'" for Strings, and "other X" otherwise. Test with 4, 7, "", "dosa", 1.5, null.

02

Model sealed interface Payment permits Card, Upi, Cash as records with an amount in paise (Card also has boolean international). Write feePaise with no default: international cards 3%, domestic cards 2%, UPI and cash free.

03

Write static String toJson(Object o) with a pattern switch that handles null, String (quoted), Number, Boolean, and List<?> (recursively, using a block and yield), and throws IllegalArgumentException otherwise.

Explain it without notes

01

What does pattern matching for switch add over a classic switch, and in which version did it become standard?

02

What is a guard, and how does it interact with case order?

03

Explain dominance with an example.

04

How does a pattern switch treat null?

05

Why is an exhaustive switch over a sealed interface without default better than one with default?

Exhaustive switch over a sealed interface Java 21+
This example needs Java 21+. The in-browser compiler is Java 17: install JDK 21 or newer and run it with "java Main.java".

Expected output

Circle[r=1.0] area=3.14 circle
Square[side=3.0] area=9.0 square
Rect[w=2.0, h=5.0] area=10.0 rect
Rect[w=4.0, h=4.0] area=16.0 rect that is really a square
Circle[r=0.0] area=0.0 a dot