liveBook · Manning

Case statement

As explained in 100 Java Mistakes and How to Avoid Them

A switch statement is a Java control-flow statement that selects and executes a branch based on the value of an expression.

A case statement selects a switch branch by matching the switch expression. In classic Java switch syntax, execution falls through into the next case unless an explicit break, return, or equivalent exit stops it. section 3.3

Accidental fall-through

If a case omits break, multiple actions may run: a YES branch can execute its action and then continue into the NO branch. Mark intentional fall-through with // fallthrough so both readers and static analyzers can distinguish it from a mistake. section 3.3

Prefer these patterns when writing case branches:

  • Use arrow syntax, such as case YES -> actOnYes(), when Java 14 or newer is available; it prevents fall-through. section 3.3
  • Shape branches to return a value or assign one shared variable; declaring that variable final can make accidental repeated assignment fail compilation. section 3.3
  • Use static analysis to find likely omissions: SonarLint, SpotBugs, and IntelliJ IDEA provide fall-through warnings, though intentional flow may require an annotation comment. section 3.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains fall-through, prevention patterns, modern syntax, and static-analysis support, while deferring general switch semantics.
Examples
Shows button actions, intentional fall-through, character-to-Boolean conversion, and enum-based weekend selection.
What you can do after
Diagnose accidental fall-through, write non-falling-through branches, and configure analyzers to recognize intentional flow.
How it connects
Connects case branches with switch statements, switch expressions, break statements, enum initialization, and static analysis.

Also explained in

Compare how 9 books explain case statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.