Java Trail: Loops
This series of articles covers all types of loops in the Java language.
-
while loop
A while loop runs statements repeatedly until a condition becomes false.
-
for loop
Examples of for loops in Java. Both traditional for loops and for each loops ("enhanced for loops") are explained in detail.
-
for each loop
For each loops are written as 'for (Type x : iterable) { ... }' and can be used to iterate over arrays or collections.
-
do…while loop
A do…while loop runs statements once, checks the loop condition and continues to run the statemnets repeatedly until the condition becomes false.
-
Java Loops: break
Examples of how to the break statement can be used to terminate a loop from within the loop body, before the loop condition becomes false.
-
Java Loops: continue
Examples and illustrations of how to the continue statement can be used to control loop iteration.
-
Beware of accidental semicolons in while and for loops!
An extra semicolon after while(...) or for(...) is interpreted as the body of the loop. The semicolon itself is a no-op statement and therefor often causes the program malfunction or crash.