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.
Ordering case labels - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
Ordering case labels
- [Instructor] A switch statement or expression can have different types of case labels, ones that contain guarded pattern case labels, unguarded case labels, that is case labels that do not have guarded patterns, or constant case labels. When this is the case, ordering becomes important. Let's look at an example. In this switch expression, I move the position of the third case label to the top, which simply prints the salary of the employee. By the way, this is an unguarded case label. Let's move it to the top. Two compile errors pop up in the second and the third case labels. These two case labels are guarded pattern case labels. What does the compile error contain? Well, both contains this statement "Label is dominated by a preceding case label." This means the unguarded case label that I moved to the top cannot exist at that position. But why? When you place the more generic unguarded case label before the more specific guarded case label, the first one dominates the second one…
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.