☕ Java
Advanced
What is pattern matching for switch in Java?
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.