Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Control Flow — Loops, Conditionals & Switch

Explain switch pattern matching (Java 21) and how it changes the way you'd write type-dispatch code.

Level III · MidControl Flow — Loops, Conditionals & Switch
Short answer

Java 21 lets case labels match on type patterns and even deconstruct records, with optional guards via 'when', so you can dispatch on the runtime shape of an object in one exhaustive switch.

Explanation

Over a sealed hierarchy the compiler verifies all permitted subtypes are handled, eliminating the default branch and catching gaps at compile time. This replaces long instanceof-and-cast chains and is the idiomatic way to do closed-set polymorphism without scattering behavior across subclasses.

Common mistakes
  • Writing long instanceof-and-cast chains instead of pattern matching in switch.
  • Forgetting case order matters when patterns dominate each other.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Control Flow — Loops, Conditionals & Switch.

Practise free

More on Control Flow — Loops, Conditionals & Switch