EMZETT.
Login

Loops

In short: Java provides three loop types for executing code repeatedly: for, while, and do...while — depending on whether the number of iterations is known in advance or depends on a condition at runtime.

In more detail: The choice of loop type depends on when the exit condition is checked: pre-test loops (for, while) check before every iteration, the post-test do...while loop always executes the body at least once. break and continue additionally control the flow within a loop.

In Depth

LoopControlCheck timingTypical use
forpre-testbefore every iterationfixed/known number of iterations
for-eachpre-testper elementiterate over an array/collection
whilepre-testbefore every iterationunknown number, condition-dependent
do-whilepost-testafter every iterationat least 1 iteration guaranteed
// Classic for loop - when the number of iterations is known in advance
for (int i = 0; i < 5; i++) { System.out.println(i); }
 
// while - when it's unclear how often the loop will run
int n = 100;
while (n > 1) { n = (n % 2 == 0) ? n / 2 : n * 3 + 1; } // Collatz sequence
 
// for-each - iterate over elements instead of indices
for (String name : List.of("Anna", "Ben")) { System.out.println(name); }

Choosing the right loop type is more than pure taste: a for loop immediately signals to the reader “a known, fixed number of iterations runs here” (e.g. exactly 5 times), a while loop signals “the number here depends on a runtime condition” (the Collatz example above can theoretically run for an arbitrarily long time). A for-each should always be chosen when you just want to iterate over ALL elements of a collection, with no need for the index itself — it’s less error-prone (no off-by-one risk) than an index-based for loop.

See also: For Loop, While Loop, do-while Loop, Break/Continue