A switch expression (Java 14) returns a value, uses the arrow (case X ->) syntax and has no fall-through, so you never need break. The old switch statement only executed code and fell through to the next case if you forgot a break.
Key Points: • case A, B -> value lets one branch handle several labels. • Arrow cases don't fall through, which removes a whole class of bugs. • A switch expression must be exhaustive: cover every value or add a default. For enums, listing all constants is enough. • Use yield to return a value from a block: case X -> { log(); yield 10; }. • The arrow form can also be used in a switch statement that returns nothing.
Code Example:
import java.time.DayOfWeek;
public class SwitchExpressionDemo {
static int workingHours(DayOfWeek day) {
return switch (day) {
case SATURDAY, SUNDAY -> 0;
case FRIDAY -> {
System.out.println(" (half day on Friday)");
yield 4;
}
default -> 8;
};
}
public static void main(String[] args) {
// Old style: easy to forget a break
int old;
switch (DayOfWeek.MONDAY) {
case SATURDAY:
case SUNDAY:
old = 0;
break;
default:
old = 8;
}
System.out.println("Old switch: " + old);
for (DayOfWeek d : new DayOfWeek[]{DayOfWeek.MONDAY, DayOfWeek.FRIDAY, DayOfWeek.SUNDAY}) {
System.out.println(d + " -> " + workingHours(d));
}
}
}Output:
Old switch: 8 MONDAY -> 8 (half day on Friday) FRIDAY -> 4 SUNDAY -> 0
Good to Know: Interviewers often ask "What is yield, and how is it different from return?" yield gives a value back from a block inside a switch expression. return would exit the whole method, so it isn't allowed there.
Interview Tip: A concise interview answer is:
"A switch expression returns a value, uses the arrow syntax with no fall-through, and must cover every case. It removes the forgotten-break bug, lets one case handle several labels, and uses yield to return a value from a block."
Previous question: What are sealed classes and interfaces in Java 17?
Next question: What is pattern matching for instanceof in Java 16?