Task 5 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 — over enums, and yield

Lesson

Switching on an enum

A switch expression works beautifully on an enum: write the constant names as labels (no Type. prefix needed). If you cover every constant, you may omit default — the compiler knows the cases are exhaustive. When a branch needs more than one line, use a block with yield to produce its value.


Worked example

enum Size { S, M, L }

Size sz = Size.M;
int ml = switch (sz) {
    case S -> 250;
    case M -> 500;
    case L -> {
        int base = 500;
        yield base + 250;   // block branch produces its value with yield
    }
};
System.out.println(ml);   // 500

All three constants are covered, so no default is required. The L branch uses a block and yield.


▶ Try it: run this — a switch over the Size enum, with a block-and-yield branch.



In a switch over an enum, the labels are...


If a switch expression covers every enum constant, default is...


Type exactly what this program prints.

enum Dir { N, S, E, W }
public class Main { public static void main(String[] a){
    Dir d = Dir.E;
    String s = switch (d) {
        case N -> "up";
        case S -> "down";
        case E -> "right";
        case W -> "left";
    };
    System.out.println(s);
}}

A multi-line branch produces its value using...


True or false?