Skip to content
Codewilds

Lesson 6 of 34 · Fundamentals

Java Loops: for, while and do-while

medium20 XP3 min readFree lesson

Computers are brilliant at repetition. Instead of writing the same line a hundred times, you write it once inside a loop and let Java repeat it — for every item, for a fixed number of times, or for as long as a condition holds.

The while loop

A while loop repeats its body as long as its condition is true:

int stamina = 3;
while (stamina > 0) {
    System.out.println("Climbing... stamina " + stamina);
    stamina--;
}
System.out.println("Resting.");
Climbing... stamina 3
Climbing... stamina 2
Climbing... stamina 1
Resting.

Something in the body must eventually make the condition false. Forget stamina-- and the loop runs forever — an infinite loop. In this course, a run that takes too long is stopped with a time limit exceeded error.

The for loop

When you know how many times to repeat, for puts the three ingredients on one line — start; condition; update:

for (int i = 1; i <= 5; i++) {
    System.out.print(i + " ");
}
1 2 3 4 5

The counter i only exists inside the loop. A very common shape is looping over the indexes of a String, from 0 up to (not including) its length:

String word = "rune";
for (int i = 0; i < word.length(); i++) {
    System.out.println(i + ": " + word.charAt(i));
}

do-while

A do-while loop checks the condition after the body, so the body always runs at least once — handy for "try, then decide whether to try again".

int roll = 0;
do {
    roll++;
} while (roll < 3);

break and continue

break leaves the loop immediately; continue skips the rest of the current round and jumps to the next one:

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue; // skip even numbers
    if (i > 7) break;         // stop completely after 7
    System.out.print(i + " ");
}
1 3 5 7

Accumulating results

Most loops follow the accumulator pattern: start with an empty result, update it every round, use it after the loop. To build a String in a loop, use a StringBuilder — it is designed for appending many pieces efficiently:

int total = 0;
StringBuilder path = new StringBuilder();
for (int i = 1; i <= 4; i++) {
    total += i;
    path.append(i).append('>');
}
System.out.println(total + " " + path);  // 10 1>2>3>4>

Common mistakes

  • Off-by-one errors: i <= word.length() goes one step too far and crashes with StringIndexOutOfBoundsException. Indexes run from 0 to length() - 1.
  • Infinite loops: the condition never becomes false because the counter is never updated (or updated in the wrong direction).
  • A stray semicolon: for (int i = 0; i < 5; i++); has an empty body — the block below it runs only once.
  • Resetting the accumulator inside the loop instead of before it.

Assignment

Implement three methods in Main:

  1. sumTo(int n) — the sum 1 + 2 + … + n. sumTo(5) returns 15. If n is less than 1, return 0.
  2. countVowels(String text) — how many vowels (a, e, i, o, u, upper- or lowercase) the text contains. countVowels("Bytecode Highlands") returns 5.
  3. countdown(int from) — the numbers from from down to 1 separated by spaces, followed by "Liftoff!". countdown(3) returns "3 2 1 Liftoff!" and countdown(0) returns just "Liftoff!".

Loops in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+20 XP

Press Run to execute your code, or Submit to check it against the tests.