SwadhyAI Notes

All Java notes

Java while loop

›Short versionOpen if you only have a minute.
  • while tests the condition before the body. A false condition on entry means the body never runs.
  • The body has to change something the condition reads. Otherwise a true condition stays true.
  • A counter that stops at i < 5 visits 0, 1, 2, 3, and 4. i <= 5 includes 5.
  • do-while runs the body once, then tests. The semicolon after while (condition) is required.
  • continue in a while jumps to the test. An increment below that continue never happens.

A repeats a block for as long as its stays true. You use it when you do not know the number of passes up front: read until the input ends, or grow a value until it crosses a limit. A known count is usually a for loop, which keeps the update in the header where you can see it.

java
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

What the console shows

0
1
2
3
4

The starts at 0. The condition allows the body while i is less than 5. The body prints, then adds one. When i becomes 5 the test fails and the loop stops. The number 5 is not printed. i <= 5 would print it, and that extra pass is the usual off-by-one.

A condition that never becomes false

An is a true condition and a body that does not affect it. Delete i++ from the loop above and i stays 0, the test stays true, and the program prints 0 without end.

java
int i = 0;
while (i < 5) {
    if (i == 2) {
        continue;
    }
    System.out.println(i);
    i++;
}

One pass, then the test

A is the loop for a body that must happen before you know whether to repeat it. A menu that always draws once, then repeats while the user asks for another pass, is that shape.

java
int i = 5;
do {
    System.out.println(i);
    i++;
} while (i < 5);

The print is 5. The condition i < 5 is false at the start and still false after the increment to 6, but the body has already run. A while with the same test would have printed nothing. The semicolon after while (i < 5) closes the do statement. Leave it off and the file does not compile.

int i = 0; and the body prints i, then continues when i is 2, and only then increments. Does the loop finish?

It does not. Passes for 0 and 1 print and increment. At 2, continue returns to the test before i++. The condition i < 5 is still true, and the next pass is 2 again. Move the increment above the continue, or use a for loop, whose update runs even when the body continues.