Oracle Java SE 21 study materials
Oracle Java SE 21 study resources

Oracle Java SE 21: Controlling Program Flow

Oracle Java SE 21 · Work through your exam, one topic at a time.

All guide sections

Controlling Program Flow

Selection

A switch selector may be int-compatible (byte, short, char, int and their wrappers), String, or an enum - never long, float, double or boolean. Colon-style statement labels fall through unless you break; arrow labels never fall through and allow case 1, 2 ->. A switch expression must be exhaustive (all enum constants or a default) and every path must produce a value: use yield inside a block, or the arrow expression itself. You cannot mix colon and arrow labels in one switch, and a null selector throws NullPointerException unless the switch is a pattern switch with an explicit case null.

Java 21 pattern switches add type patterns, guards with when, and dominance rules: a more specific pattern must precede its supertype, and exhaustiveness requires a default, a total pattern such as case Object o, or full enum coverage.

Iteration

for, enhanced for, while, and do-while (which always executes at least once). Labelled break/continue (outer:) control nested loops. Removing elements inside an enhanced for triggers ConcurrentModificationException.

Traps

while (false) and statements after an unconditional return are compile errors, while if (false) is legal. The conditional operator applies binary numeric promotion across both branches, so flag ? 1 : 2.0 has type double. default placement does not affect fall-through order in a colon-style switch.

Worked rule: read a switch expression as an exhaustive map from selector to value - if any selector could fall off the end without producing a value, it will not compile.