Lesson 15 +10 XP

Java While Loop

Java While Loop

A while loop repeats a block of code as long as a condition is true.

While loop syntax

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

This prints:

0
1
2
3
4

The do while loop

The do...while loop runs the block once before checking the condition:

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

While vs do while

  • while checks the condition first; the block may never run.
  • do...while runs the block first, so it always runs at least once.

Counting up and down

You control the loop with the increment i++ or decrement i--. If you forget it, the loop never ends.

TL;DR

  • while repeats while a condition is true.
  • do...while always runs at least once.
  • Update the loop variable or you create an infinite loop.