Java ยท Chapter 15 of 42

Java While Loop

The while loop repeats a block of code as long as a condition remains true. The do-while variant runs the block at least once before checking the condition.

While loops are ideal when the number of iterations isn't known in advance, such as reading input until a sentinel value appears.

Syntax
while (condition) {
}
do {
} while (condition);

while loop

The condition is checked before each iteration; if false initially, the loop body never runs.

do-while loop

The condition is checked after the loop body runs, guaranteeing at least one execution.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    int i = 0;
    while (i < 3) {
      System.out.println(i);
      i++;
    }
  }
}
Output
0
1
2

The loop prints i and increments it while i is less than 3.

Key points

  • while checks the condition before each iteration.
  • do-while checks the condition after, so it runs at least once.
  • Forgetting to update the loop variable causes an infinite loop.
  • while loops are good for unknown iteration counts.
๐Ÿ’ก Note: Always ensure the loop condition eventually becomes false to avoid infinite loops.

๐Ÿ“ Quick Quiz

1. When is a while loop's condition checked?

2. What guarantees do-while runs at least once?

3. What causes an infinite loop?