From the course: Pattern Matching for Switch in Java 21
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
The null case label - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
The null case label
- [Narrator] What if the target or select expression object is null in a switch statement or expression? The switch would throw a null point exception. Here's how it could occur. Let's get back to a person example. Assign null instead of an employee object to person and run the program. Let's assign null here to person, save and run the program. Well, you get a null point exception. So, how is it possible to handle null values in a switch? The most intuitive way would be to test against null values outside of switch. That would be something like this. But now, with Java 21 with the switch allowing the select expression to be any reference type and with the case labels having patterns, the standard null check is not needed as it adds up unnecessary boilerplate code and could introduce errors. Therefore, now switch comes with an integrated null test by allowing a new null case label like this. Next, you'll learn how it is used.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.