Java / Java 21 Interview Questions
What are switch expressions in Java and how do they differ from switch statements?
Switch expressions (JEP 361, finalised in Java 14) make switch a value-producing expression rather than only a control-flow statement. They use the arrow (->) syntax and require exhaustiveness.
| Aspect | Switch Statement | Switch Expression |
|---|---|---|
| Produces a value | No | Yes — must be exhaustive |
| Syntax | case X: ... break; | case X -> result; or case X -> { ... yield result; } |
| Fall-through | Possible (bug-prone) | Not possible with arrows |
| Exhaustiveness | Not checked | Compiler-enforced (default required unless exhaustive) |
| Multiple labels | No | case A, B, C -> ... (comma-separated) |
// Switch STATEMENT (old style) — fall-through risk
int numLetters;
switch (day) {
case MONDAY: case FRIDAY: case SUNDAY:
numLetters = 6; break;
case TUESDAY:
numLetters = 7; break;
default:
numLetters = 8; break;
}
// Switch EXPRESSION (Java 14+) — exhaustive, no fall-through
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
}; // no default — DayOfWeek is exhaustive
// Multi-line arm with yield
int result = switch (x) {
case 1 -> 10;
case 2 -> {
int y = x * x;
System.out.println("Computing...");
yield y + 5; // yield produces the value from a block arm
}
default -> 0;
};
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
