Qualified enum constants and case null, default
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.
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.
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.
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
What does pattern matching for switch add over a classic switch, and in which version did it become standard?
What is a guard, and how does it interact with case order?
Explain dominance with an example.
How does a pattern switch treat null?
Why is an exhaustive switch over a sealed interface without default better than one with default?
Expected output
52
text / not text (or null) / not text (or null)