Java 21
Pattern Matching for ‘switch’
Copyright © Seán Kennedy
Pattern-matching for switch
• Pattern matching for switch statements and expressions was first
introduced as a preview feature in Java 17.
• Now, Java 21 finalizes the feature.
• Motivation – switch is a very natural fit for pattern matching.
Recall that pattern matching removes the need for the
instanceof-and-cast idiom.
• Other changes, such as the when clause, were motivated
by the desire to separate the case labels, patterns and
conditional logic from the business logic.
2
Copyright © Seán Kennedy
Pattern-matching for switch
• In other words, the selection of which branch to execute is
separated from what to do when we execute that branch.
• Changes include:
• case labels can include patterns and null
• case labels can include optional when clauses (“guards”)
• selector expression types broadened
• from:
• integral primitive types (excluding long), their corresponding wrapper
types, String and enums.
• to:
• integral primitive types (excluding long) and any reference type.
• enum constant case labels improved
• qualified enum constants now allowed
3
Copyright © Seán Kennedy
Pattern-matching for switch - pattern labels, null and when clauses
Copyright © Seán Kennedy
Pattern-matching for switch - selector expression types broadened
Copyright © Seán Kennedy
Pattern-matching for switch – enum constant case labels improved
Copyright © Seán Kennedy
Pattern-matching for switch
• Label “dominance”
• analogous to the catch clauses in a try statement
• unreachable code (label)
Copyright © Seán Kennedy
Pattern-matching for switch
• Label “dominance”
• unconditional pattern and default
Copyright © Seán Kennedy
Pattern-matching for switch
• Exhaustiveness
Copyright © Seán Kennedy