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.
Guarded pattern case labels - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
Guarded pattern case labels
- [Narrator] What if you need to further test a value to see if it matches some pattern within the switch for a particular case label? This leads to writing conditional code on the right hand side of the case label. Here's an example. Here in line number 13, if the employee's salary is greater than 100,000, we want to say highly paid. Similarly, in line number 19, if the student's mark is greater than or equal to 75, we want to say the grade is a distinction, something like that. By the way, yield here is a key word introduced to switch expressions sometime back to be able to return some value from a particular case. It is typically used at the end of a code block to return a value, often after performing other functions earlier in the block. Yield is usually used when curly braces are used in the right side of the case label to perform some function in multi-line case blocks like in this example, back to the switch. Checking conditions this way adds a lot of clutter to the code…
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.