Pattern Matching for Switch in Java 21

Pattern Matching for Switch in Java 21

41mIntermediate2025-06-20

Authors

Buddhini Samarakkody

Buddhini Samarakkody

Java Engineer, Author, Instructor

Course details

The course is designed for intermediate Java developers looking to upskill and grow their career. Join instructor Buddhini Samarakkody as she covers the essentials of the pattern matching feature for switch statements and expressions which was introduced in Java 21. Learn how patterns can be used in case labels of a switch statement or expression, using guarded patterns to further test if a value matches a pattern, the use of Java Records in switch, along with pattern matching. Along the way, Buddhini outlines the use of the null case label to avoid NullPointerExceptions in switch statements or expressions. By the end of this course, you’ll be equipped with the skills you need to write more readable, more concise, more powerful code.


Learning objectives
Identify the need for pattern matching for switch.
Write switch statements or expressions that contain patterns in case labels.
Demonstrate how to use null case labels in a switch statement or expression to prevent NullPointerExceptions.
Write switch statements or expressions that contain guarded patterns in case labels to further test if a value matches a pattern.
Demonstrate the use of switch statements and expressions that use Java Records for pattern

Skills covered

JavaOracleProgramming LanguagesSoftware DevelopmentOne-Off

Concepts

Introduction

  • Learning about pattern matching for switch
  • What you should know
  • Tour of CoderPad

The Background to Pattern Matching

  • What is pattern matching
  • Motivation - Pattern matching for instanceof
  • Evolution of switch in Java

Pattern Matching for Switch

  • Patterns in case labels
  • Using patterns in case labels
  • The null case label
  • Using the null case label
  • Guarded pattern case labels
  • Using guarded pattern case labels

Further Considerations

  • Ordering case labels
  • Exhaustiveness of a switch block
  • Using record patterns with switch

Conclusion

  • Next steps
40,000 Toman