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;vis a copy of the element value or reference, so assigning tovdoes not change the array. breakexits the nearest loop or labeled block;continueskips 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
fororwhilecreates 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 areturn.for (;;)is a legal infinite loop.continuein ado-whilestill evaluates the condition.- Removing elements from a collection inside an enhanced
forusually throwsConcurrentModificationException.