EMZETT.
Login

Pre-Test Loop

Kopfgesteuerte Schleife Image: Taylor, CC BY-SA 4.0, Wikimedia Commons

In short: A loop whose exit condition is checked BEFORE every iteration — if it’s already false on the first check, the body doesn’t run at all.

In more detail: for and while are both pre-test loops in Java. This distinguishes them from the post-test do...while loop, where the condition is only checked AFTER the first iteration — so the body is guaranteed to run at least once.

In Depth

int n = 10;
 
// while: pre-test - condition checked first
while (n > 0) {
    System.out.println(n);
    n--;
}
 
// for: also pre-test, just with a fixed, structured header
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
 
// Runs 0 times, because the condition is false from the start
int x = 5;
while (x < 0) {
    System.out.println("never printed");
}

The vast majority of loops in real Java code are pre-test (for and while), because the typical pattern is “as long as/for all elements that meet a condition, do X” — and here it’s usually completely plausible that X shouldn’t run at all if the condition doesn’t hold from the start (e.g. iterating over an empty list: zero iterations is the expected, correct behaviour here). The post-test do-while loop remains the exception for the rarer cases where at least one iteration MUST be guaranteed before anything can even be checked.

for vs. while — which form when?

Both are pre-test and can be reformulated into each other, but differ in typical usage: for bundles initialization, condition, and update into one header and is therefore especially suitable when the number of iterations is known IN ADVANCE or clearly countable (e.g. “for each element of an array”). while fits better when the exit condition depends on something that only becomes known WHILE the loop is running (e.g. “as long as there are still lines to read in a file”):

// for: number of iterations known from the start
for (int i = 0; i < array.length; i++) { ... }
 
// while: exit depends on something only known at runtime
String line;
while ((line = reader.readLine()) != null) { ... }

Infinite loops as a special case

for (;;) and while (true) are both valid, deliberate infinite loops — they run as pre-test loops, but their condition is constantly true (or, for for (;;), simply omitted, which Java interprets as “always true”). Such constructs aren’t a mistake, but a deliberate pattern for server loops, event loops, or cases where the exit should happen via a break in the middle of the body, rather than via a fixed header condition.

See also: Post-Test Loop, For Loop, While Loop