Java SE 11 Developer study materials
Java SE 11 Developer study resources

Java SE 11 Developer: Controlling Program Flow

Java SE 11 Developer · Work through your exam, one topic at a time.

All guide sections

Controlling Program Flow

This domain checks whether you can predict exactly which branches and iterations execute, including fall-through and labelled jumps.

if and the conditional operator

The if condition must be boolean - Java has no truthiness, so if (x = 0) is a compile error when x is an int. The ternary operator requires compatible second and third operands; if one is a primitive and the other its wrapper, the result type is the primitive and a null wrapper unboxes to a NullPointerException.

switch

Allowed selectors are byte, short, char, int, their wrappers, String and enum constants - never long, float, double or boolean. Case labels must be constant expressions assignable to the selector type, and duplicates are a compile error. Without break execution falls through, which the exam tests constantly. default may appear anywhere and only runs when no case matches. A null String selector throws NullPointerException; so does an unboxed null wrapper.

Loops and labels

while tests before, do-while tests after so the body runs at least once. The basic for allows multiple initializations and updates separated by commas. The enhanced for works on arrays and Iterable; modifying a collection inside it usually throws ConcurrentModificationException. Labels let break label; exit an outer loop and continue label; skip to the next iteration of an outer loop.

Worked example

A labelled continue inside nested loops: outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) continue outer; System.out.print(i + "" + j + " "); } } prints 00 10 20. Reasoning: continue outer abandons the inner loop and starts the next iteration of the outer loop, so j never reaches 2.

Traps

Forgotten break in switch; declaring a variable in one case and reusing it in another without braces (scope is the whole switch block); unreachable statements after while (true) {} without a break, which is a compile error; do { } while (false); being perfectly legal.