Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Control Flow — Loops, Conditionals & Switch

Compare a traditional switch statement with a switch expression (Java 14+). When would you reach for the new form?

Level II · JuniorControl Flow — Loops, Conditionals & Switch
Short answer

The old switch is a statement with fall-through by default, requires break, and cannot produce a value directly, which makes accidental fall-through a classic bug source.

Explanation

The arrow switch expression (case X -> ...) has no fall-through, can yield a value to assign, and the compiler enforces exhaustiveness when switching over an enum or sealed type. Reach for the expression form whenever you are mapping an input to a value, because it is both safer and more concise.

Common mistakes
  • Forgetting that switch expressions must be exhaustive and cannot fall through.
  • Using the old switch where a value-returning switch expression is cleaner.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Control Flow — Loops, Conditionals & Switch.

Practise free

More on Control Flow — Loops, Conditionals & Switch