Loops: while, do-while, for, for-each

Four ways to repeat, and when to use each.

Repeating work

while — test first, may run zero times:

while (n > 0) { n--; }

do-while — runs the body at least once, tests after:

do { line = read(); } while (line != null);

for — when you have an index; init, condition, update in one header:

for (int i = 0; i < 5; i++) { System.out.println(i); }

Enhanced for (for-each) — iterate every element of an array or collection without an index:

for (String name : names) {
    System.out.println(name);
}

Reach for for-each by default — it's the clearest and avoids off-by-one errors. Use the indexed for only when you actually need the index.

NORMAL ~/memra/learn/java-from-zero/loops utf-8 LF