Java SE 8 Programmer I (OCAJP 8) study materials
Java SE 8 Programmer I (OCAJP 8) study resources

Java SE 8 Programmer I (OCAJP 8): Using Loop Constructs

Java SE 8 Programmer I (OCAJP 8) · Work through your exam, one topic at a time.

All guide sections

Using Loop Constructs

Using Loop Constructs

This domain tests while, do-while, basic for, and enhanced for, plus break, continue, labels, and nested loops. You need to trace iterations precisely and recognize when code does not compile or never terminates.

Loop forms

  • while (condition) tests before each iteration; do { ... } while (condition); tests after, so it runs at least once and needs a semicolon after the condition.
  • for (init; condition; update) allows multiple initialization or update expressions separated by commas, but they must share a compatible type. Variables declared in the initialization are scoped to the loop.
  • Enhanced for (Type v : arrayOrIterable) visits each element; v is a copy of the element value or reference, so assigning to v does not change the array.
  • break exits the nearest loop or labeled block; continue skips to the next iteration. With a label, both can target an outer loop.

Worked example

int[] a = {1, 2, 3};
for (int v : a) {
  v = v * 2;
}
System.out.println(a[0]);

The enhanced loop variable v receives a copy of each int element. Reassigning v leaves the array unchanged, so the output is 1. If the array held mutable objects, calling a mutator on v could still change shared object state.

Traps

  • A stray semicolon after for or while creates an empty body; the following block runs once.
  • while (false) { ... } is legal but the body is unreachable, which can cause a compile error if it is the only statement after a return.
  • for (;;) is a legal infinite loop.
  • continue in a do-while still evaluates the condition.
  • Removing elements from a collection inside an enhanced for usually throws ConcurrentModificationException.