Skip to main content
PreparationZone Logo
PrepZone

Switch Expressions and Text Blocks

Switch that returns a value with no fall-through, plus multi-line strings that stay readable.

Pass checkpoint below

Read these first

Why this matters

  • Missing break is one of the oldest bug sources in C-family languages, and switch expressions remove the possibility entirely.
  • Exhaustiveness means adding an enum constant breaks the build rather than silently falling into default.
  • Embedded JSON, SQL and HTML are everywhere, and escaped single-line strings make them unreadable and error-prone.

The old switch statement

Java
Loading compiler…

Four problems: the variable must be declared outside and uninitialised, each case needs an explicit break, each grouped label needs its own line, and the whole thing is a statement so it cannot be used inline.

Switch expressions

Java
Loading compiler…
Old switch statement
case + breakForget break and it falls through
Assigns to a variableCannot be final
Switch expression
case A -> valueNo fall-through
Returns a valueAssign directly to a final variable
ExhaustiveCompiler checks every case
Arrow labels do not fall through and the switch produces a value. Over an enum or sealed type the compiler also checks that every case is covered.

What the arrow form changes

  • No fall-through. Each arm runs only its own branch, so break is gone.
  • Multiple labels per arm, comma-separated.
  • It is an expression, so it can be assigned, returned, or passed as an argument.
  • Exhaustiveness is required when it produces a value. Over an enum, covering every constant is enough and default is unnecessary.
Java
Loading compiler…

Multi-line arms with yield

When an arm needs more than one statement, use a block and yield the value.

Java
Loading compiler…

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 4 sections

  • The colon form still exists
  • Switch on what
  • Text blocks
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.