Skip to main content
Java 14 · Topic 1 of 2

Switch expressions

Definition​

A switch expression returns a value and uses ->, so there is no fall-through and no break. The compiler checks that every case is covered, which makes it safer than the old switch statement.

Example code​

Turning a day into a number of hours

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

class Demo {
static int workHours(Day day) {
return switch (day) {
case MON, TUE, WED, THU -> 8;
case FRI -> 6;
case SAT, SUN -> 0; // if a case is missing, it does not compile
};
}

public static void main(String[] args) {
for (Day day : Day.values()) {
System.out.println(day + ": " + workHours(day));
}
}
}

// Output:
// MON: 8
// TUE: 8
// WED: 8
// THU: 8
// FRI: 6
// SAT: 0
// SUN: 0

Finished this page? Track your progress (saved only in your browser).