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.
Using the null case label - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
Using the null case label
- [Instructor] In the previous video I mentioned a null case label. Here's how that null case label can be used in the person example. It's added simply as just another case label in the switch. You can add a case label as case null and the arrow operator as usual, and then return a suitable value. I'm simply returning a string value of null. In line number four here in the main method, person is assigned with null, so the select expression becomes null. Let's run it. Well, it won't throw the null point exception now. It returns the value that was specified in the null case label, which is the string null in this case. The behavior switch when the selector expression is null is determined by the null case label. A switch statement or expression always executes the code associated with the matching case label. So if a null value is passed to the selector expression, the switch can gracefully handle the situation if a null case label is present, and that's what happened in the demo.
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.