Task 1 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 — producing a value

Lesson

A switch that returns a value

A modern switch expression uses arrow labels (case X ->) and produces a value you can assign to a variable. Each branch is one expression; there is no fall-through and no break is needed. For an int or String switch you must include a default so every input is covered.


Worked example

int day = 3;
String name = switch (day) {
    case 1 -> "Mon";
    case 2 -> "Tue";
    case 3 -> "Wed";
    default -> "?";
};
System.out.println(name);   // Wed

Compare with the old style: no break, no accidental fall-through, and the whole thing is an expression with a result.


▶ Try it: run this — the switch expression yields a String that is assigned to name.



A switch expression...


With arrow (->) labels, fall-through between cases...


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    int n = 2;
    String s = switch (n) {
        case 1 -> "one";
        case 2 -> "two";
        default -> "many";
    };
    System.out.println(s);
}}

For a switch expression over an int, a default branch is...


True or false?