Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

11.2 Switch expressions — grouping labels

Lesson

Several values, one branch

When several inputs should give the same result, list them in one label separated by commas: case 6, 7 -> "weekend". This replaces the old trick of stacking empty case lines to share a body, and it reads far more clearly.


Worked example

for (int d = 1; d <= 7; d++) {
    String type = switch (d) {
        case 6, 7 -> "weekend";
        default   -> "weekday";
    };
    System.out.println(d + ": " + type);
}
// 1: weekday ... 5: weekday, 6: weekend, 7: weekend

Days 6 and 7 share the single "weekend" branch; every other day falls to default.


▶ Try it: run this — days 6 and 7 map to "weekend" through one grouped label.



To make several values share one branch, you...


case 4, 6, 9, 11 -> 30 means...


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    for (int n = 1; n <= 4; n++) {
        String s = switch (n) {
            case 1, 3 -> "odd";
            default -> "even";
        };
        System.out.println(s);
    }
}}

Grouped labels replace the old style of...


True or false?