What is pattern matching for switch in Java?
Why Interviewers Ask This
Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.
Answer
Pattern matching for switch (Java 21, finalized) extends switch expressions to match on type patterns, guard patterns, and record patterns. Example: String result = switch (obj) { case Integer i -> "int: " + i; case String s when s.length() > 5 -> "long string"; case null -> "null"; default -> "other"; };. This eliminates lengthy if-instanceof-cast chains. With sealed classes, all subtypes can be covered exhaustively. Guard patterns (when clause) add conditions beyond type matching. This is a major step towards functional-style pattern matching in Java, aligning it with modern languages like Kotlin, Scala, and Haskell.
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong Java candidates.