Java: Beware of accidental semicolons in while and for loops!

In the following code…

while(cond); {
    // ...
}

…the extra semicolon is actually interpreted as a no-op statement. Since braces are optional for single statement while loops, this causes the compiler to view the ; as a single statement body, followed by a separate block statement.

while(cond)
    ; // <-- loop body!

{
    // Not part of the loop!
}

This can have catastrophic consequences.

Example: Program enters an infinite loop since i++ is never executed
int i = 0;
while (i < 10); {
    i++;
}

Same issue applies for for loops.

Example: "Hello" printed once since the print statement is not part of the loop body
for (int i = 0; i < 10; i++); {
    System.out.println("Hello");
}

Comments