Java while, do/while, for and for-each Loops (OCP 21)
The OCP Java 21 rules for loops: while versus do/while, the three optional parts of a for loop, multiple loop variables, loop variable scope, for-each over arrays and Iterable, nested loops, infinite loops and the loop conditions the compiler rejects.
kvi5hnuCode Sprout team member10 min readOn this page
Loops repeat a statement or block. Java has four: while, do/while, the basic for and the enhanced for (for-each). The exam won't ask you to write clever loops. It asks you to trace them precisely: how many times the body runs, what a variable holds at the end, and whether the code compiles at all. This article covers each loop and the edge cases that show up on the exam. Article 15 covers break, continue, labels and unreachable code.

The while loop
int fuel = 6;
int laps = 9;
while (laps > 0 && fuel > 0) {
laps--;
fuel--;
}
System.out.println(laps + " laps left"); // 3 laps left
- The condition must be a
booleanexpression.while (1)fails with "int cannot be converted to boolean". There's no C-style truthiness. - The condition is tested before each iteration, so the body may run zero times.
- The body can be a single statement without braces. As with
if, only the first statement is part of the loop, whatever the indentation.
int seats = 3;
while (seats < 3) { // false the first time: body never runs
System.out.println("Seat free!");
seats++;
}
The do/while loop
int tries = 0;
do {
tries++;
} while (false);
System.out.println(tries); // 1
- The body runs first and the condition is checked afterwards, so the body runs at least once.
- The statement ends with a semicolon after the condition. Leaving it out is a compile error.
- Braces are optional for a single statement:
do x++; while (x < 5);compiles. - A variable declared inside the body is not in scope in the condition.
do { int k = 1; } while (k < 3);fails with "cannot find symbol".
The basic for loop
for (int i = 0; i < 5; i++) {
System.out.print(i + " "); // 0 1 2 3 4
}
The header has three parts separated by two semicolons:
- Initialization runs once. It declares variables or runs expression statements.
- Condition is checked before every iteration, including the first.
- Update runs after every iteration, before the condition is checked again.
Edge cases the exam uses
All three parts are optional, but the semicolons aren't. for ( ; ; ) is an infinite loop. for () doesn't compile.
Several variables, one type. The initialization can declare several variables, but only in a single declaration of one type. The update can contain several expressions separated by commas:
int i = 0;
for (long a = 0, b = 3; i < 4 && a < 10; i++, a++) {
System.out.print(a + " ");
}
System.out.print(i); // 0 1 2 3 4
for (long a = 0, int b = 3; …) doesn't compile: one declaration can't have two types. A declared variable doesn't need an initializer (for (int i = 0, j; …) compiles if j is never read), and the initialization can be an expression list instead (for (i = 0, j = 10; …)).
No redeclaring. If i already exists in the method, for (int i = 2; …) fails with "variable i is already defined". Reuse it with for (i = 2; …) or for ( ; i < 4; i++).
Scope. A variable declared in the initialization exists only inside the loop. Reading it after the loop is a compile error. A variable declared before the loop and assigned in it is still available afterwards.
Anything can go in the update. for (int i = 0; i < 3; i++, System.out.print(i)) compiles. Only expression statements are allowed there: assignments, ++/--, method calls and new.
Counting down
Reverse loops are where off-by-one mistakes hide:
for (var counter = 5; counter > 0; counter--) System.out.print(counter + " "); // 5 4 3 2 1
for (var counter = 4; counter > 0; counter--) System.out.print(counter + " "); // 4 3 2 1
for (var counter = 4; counter >= 0; counter--) System.out.print(counter + " "); // 4 3 2 1 0
When you see -- in a loop on the exam, write down the first value, check the condition at the boundary, and count.
Modifying the loop variable in the body
It compiles, but it changes the iteration count in ways that are easy to misread:
for (int i = 0; i < 10; i++) i = 0; // infinite: i goes 0 → 1 → 0 → 1 …
for (int j = 1; j < 10; j++) j++; // runs 5 times: j = 1, 3, 5, 7, 9
The for-each loop
String[] names = {"Ada", "Linus", "Grace"};
for (var name : names) {
System.out.println(name);
}
The right side must be either:
- an array, or
- an object whose type implements
java.lang.Iterable:List,Set,Queue,Deque, anyCollection, or your own class.
That excludes a String (it's neither an array nor an Iterable; use toCharArray() or chars()) and a Map (iterate over map.keySet(), map.values() or map.entrySet()). Both fail with "for-each not applicable to expression type".
The left side declares a variable whose type must accept each element: the element type, a supertype, var, or a type reached by widening or unboxing. for (int sloth : new String[3]) fails, while for (long n : new int[]{1, 2}) and for (Integer n : new int[]{1}) compile. The variable can be final.
Things to know about how it runs:
- Each iteration assigns a fresh value to the loop variable. Assigning to the variable changes nothing in the array or collection.
- There's no index. If you need one, use a basic
forloop. - Removing elements from a collection inside a for-each over it usually throws
ConcurrentModificationException. UseremoveIfor an explicitIterator. - A
nullarray or collection on the right side throws aNullPointerException.
Nested loops
Any loop can contain any other. For each pass of the outer loop, the inner loop runs to completion:
int[][] grid = {{4, 8, 1, 6}, {2, 7, 3, 3}, {9, 0, 5, 1}};
for (int[] row : grid) { // 3 passes
for (int i = 0; i < row.length; i++) { // 4 passes each
System.out.print(row[i] + "\t");
}
System.out.println();
}
When you trace mixed nesting, remember that an inner do/while runs at least once on every pass of the outer loop, even when its condition is already false.
Infinite loops and conditions the compiler can see
A loop whose condition never becomes false runs forever unless something inside it (break, return, an exception) leaves it. The compiler doesn't complain about ordinary infinite loops, because it can't know the values of variables at runtime. Two classic traps:
- Overflow:
for (byte b = 0; b < 200; b++)never ends, because abytewraps from 127 to -128 before it reaches 200. - Floating point:
for (double d = 0; d != 1.0; d += 0.1)never ends, because ten additions of 0.1 give 0.9999999999999999. Withd < 1.0the loop runs 11 times, not 10.
The compiler does evaluate a constant condition: a literal or a final variable initialized with a constant. That leads to a rule that looks odd at first:
| Code | Result |
|---|---|
while (false) { … } | Compile error: unreachable statement |
for ( ; false ; ) { … } | Compile error: unreachable statement |
do { … } while (false); | Compiles: the body runs once |
final boolean f = false; while (f) { … } | Compile error: f is a constant |
boolean f = false; while (f) { … } | Compiles: f isn't a constant |
while (true) { } followed by another statement | Compile error: the next statement is unreachable |
if (false) { … } | Compiles: if is deliberately exempt |
Article 15 explains these unreachable-code rules in full.
What's current
- Loop syntax is unchanged through Java 25.
- Java 22 lets an unused loop variable be unnamed (
for (var _ : items)), on the Java 25 exam only.
Exam traps from this article
A complete example
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
public class Solution {
// Any Iterable works on the right side of a for-each loop
record Countdown(int from) implements Iterable<Integer> {
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int next = from;
@Override public boolean hasNext() { return next >= 0; }
@Override public Integer next() { return next--; }
};
}
}
public static void main(String[] args) {
System.out.println("-- while: zero or more times --");
int laps = 9, fuel = 6;
while (laps > 0 && fuel > 0) {
laps--;
fuel--;
}
System.out.println("laps left: " + laps);
int seats = 3;
while (seats < 3) {
System.out.println("never printed");
seats++;
}
System.out.println("-- do/while: at least once --");
int tries = 0;
do {
tries++;
} while (false);
System.out.println("tries = " + tries);
System.out.println("-- for: several variables, reverse order --");
int i = 0;
for (long a = 0, b = 3; i < 5 && a < 10; i++, a++) {
System.out.print(a + b + " ");
}
System.out.println("| i after loop = " + i);
for (var counter = 4; counter >= 0; counter--) {
System.out.print(counter + " ");
}
System.out.println();
System.out.println("-- floating-point loop counter --");
int steps = 0;
for (double d = 0; d < 1.0; d += 0.1) {
steps++;
}
System.out.println("steps of 0.1 below 1.0: " + steps);
System.out.println("-- for-each over an array, a List and a custom Iterable --");
String[] names = {"Ada", "Linus", "Grace"};
for (var name : names) {
System.out.print(name.length() + " ");
}
System.out.println();
for (String name : names) {
name = name.toUpperCase(); // changes only the loop variable
}
System.out.println(String.join(",", names));
for (int n : new Countdown(3)) {
System.out.print(n + " ");
}
System.out.println();
System.out.println("-- nested loops --");
int[][] grid = {{4, 8, 1}, {6, 2, 7}};
for (int[] row : grid) {
for (int c = 0; c < row.length; c++) {
System.out.print(row[c] + (c < row.length - 1 ? " " : ""));
}
System.out.println();
}
int tank = 9;
while (tank > 0) {
do {
tank -= 3;
} while (tank > 4);
tank--;
System.out.print(tank + ", ");
}
System.out.println();
System.out.println("-- changing a List inside for-each --");
List<String> birds = new ArrayList<>(List.of("jay", "owl", "crow"));
try {
for (String b : birds) {
if (b.equals("jay")) birds.remove(b);
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}
birds.removeIf(b -> b.startsWith("o"));
System.out.println(birds);
}
}
Output:
-- while: zero or more times --
laps left: 3
-- do/while: at least once --
tries = 1
-- for: several variables, reverse order --
3 4 5 6 7 | i after loop = 5
4 3 2 1 0
-- floating-point loop counter --
steps of 0.1 below 1.0: 11
-- for-each over an array, a List and a custom Iterable --
3 5 5
Ada,Linus,Grace
3 2 1 0
-- nested loops --
4 8 1
6 2 7
2, -2,
-- changing a List inside for-each --
ConcurrentModificationException
[crow]
Points to notice:
- The second
whilenever runs its body. Thedo/whileruns once even though its condition isfalse. iwas declared before theforloop, so it's still available afterwards, holding 5.aandbaren't.- The
doubleloop runs 11 times, because of rounding. - Assigning
name = name.toUpperCase()in a for-each changes only the loop variable, so the array is untouched. Countdownworks in a for-each because it implementsIterable<Integer>, and eachIntegeris unboxed intoint n.- Removing an element inside the for-each throws
ConcurrentModificationException, whileremoveIfis safe.
Common questions
When should I use while versus do/while?
Use while when the body might not need to run at all (reading until end of input, waiting for a condition). Use do/while when the body must run once before the check makes sense (showing a menu, then asking whether to repeat).
Is for (;;) better than while (true)?
They're equivalent. Both are infinite loops that need a break, return or exception to end, and both make any statement directly after them unreachable.
Why can't I declare int i = 0, long j = 0 in a for loop?
The initialization is a single local variable declaration, and a declaration has exactly one base type. Declare one of the variables before the loop instead.
Is the for-each loop slower than an indexed loop?
Over arrays they compile to almost the same bytecode. Over an ArrayList, the iterator adds a little overhead, which the JIT usually removes. Over a LinkedList, for-each is much faster than calling get(i) in a loop, which is O(n) for each call.
Can I iterate over a Map with for-each?
Not directly. Use map.entrySet(), keySet() or values(), which are all Collections, or map.forEach((k, v) -> …).
Summary
whilechecks first and may run zero times.do/whilechecks last, always runs once and ends with;.for (init; condition; update): every part is optional, both semicolons are required, the initialization holds one declaration of one type, and the update holds a comma-separated list of expressions.- Variables declared in a
forheader exist only inside the loop. - for-each works only on arrays and
Iterables, never onStringorMap. Assigning to the loop variable doesn't change the source. - Watch nested loops, reverse loops and loop variables changed in the body.
- A constant
falsecondition onwhileorforis unreachable code. Ondo/whileit's fine. A constanttruemakes the next statement unreachable unless the loop canbreak.
Practice quiz
Test yourself with the loops quiz: 10 exam-style questions with explanations.
Previous: Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)
Next: Java break, continue, Labels, return and Unreachable Code (OCP 21)
Related reading
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- Writing a Class Loader and Bytecode Verification in Java
- Class Loading in Java: The Loading Process, Loader Hierarchy and Namespaces

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.