Java: while loop

while (awake) {
    writeCode();
    drinkCoffee();
}

A while loop executes instructions repeatedly until the condition becomes false.

while (condition) { true false instructions }

Unless you want the loop to run indefinitely, it's important that instructions eventually make condition false.

Example:

int i = 3;
while (i >= 0) {
    System.out.println("Count down: " + i);
    i--;
}
Count down: 3
Count down: 2
Count down: 1
Count down: 0

Example: Infinite loop

while (true) {
    System.out.println("Looping forever!");
}

If the condition is initially false the body will not execute at all.

Example:

while (false) {
    System.out.println("Never printed");
}

(Doesn't even compile due to "Unreachable statement".)

Optional Braces

For single statement bodies, the braces are optional, just as with if and for statements.

Example: These two snippets are equivalent:

while (!successful) {
    tryAgain();
}
System.out.println("Success!");
while (!successful)
    tryAgain();

System.out.println("Success!");

The official style guide does however madate the use of braces for safety.

Accidental semicolon

There should not be a semicolon after the loop declaration:

while (…); { … } // bad!

See Beware of accidental semicolons in while and for loops!

Comments

Be the first to comment!