pattern guard
An extra boolean condition attached to a pattern, so a case only matches when both the type and the condition fit.
In more detail
In a switch the guard follows the keyword when, as in case String s when s.isBlank(). With instanceof the same effect comes from combining the pattern with && and a condition. Guards keep a business rule next to the type test it refines.
Example
case String s when s.isBlank() -> "empty";Related terms
- pattern matching — Testing a value against a shape, such as a type, a range or the values of its properties, and optionally extracting parts of it in the same step.
- switch expression — A switch construct that produces a value, with one arm per case and no fall-through between them.
Taught in
- Pattern Matching And Text Blocks — Modern Java: Virtual Threads & High-Throughput Services
- Sealed Types, Casts And Pattern Matching — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Sprint: Object-Oriented Java — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Thread Safety: Locks And Atomics — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep