An arrow switch is an expression, so it can be assigned. Use yield when a branch needs a block of statements before producing its result.
for (int month : List.of(1, 4, 12)) {
String quarter = switch (month) {
case 1, 2, 3 -> "Q1";
case 4, 5, 6 -> "Q2";
case 7, 8, 9 -> "Q3";
default -> {
String q = "Q4";
yield q + " (year end)";
}
};
System.out.println("month " + month + " -> " + quarter);
}
month 1 -> Q1
month 4 -> Q2
month 12 -> Q4 (year end)
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30