AI Hints
Home›Java Tutorial›while Loops, do while and for Loops
Java · Lesson 37 of 120

while Loops

Repeat while true.

⏱ 2 min read▶ Video at 47:20🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A loop repeats code. A while loop keeps repeating, as long as its condition stays true. Computers are great at repeating things, quickly, without getting bored.

  • Repeat code
  • While the condition is true
  • Never bored

Counting to five

Count starts at one. While count is five or less, the loop body runs. It prints the count, then adds one. Then Java checks the condition again. When count reaches six, the condition is false, and the loop stops. Run it. One to five, and count ends at six.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 5) {
            System.out.println("Count is " + count);
            count++;
        }
        System.out.println("Done! count is now " + count);
    }
}
Output
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Done! count is now 6

Until a goal is reached

While loops are perfect when you don't know how many times to repeat. Savings start at one hundred, and grow ten percent each year. How many years until we reach two hundred? Run it. Eight years, with two hundred and fourteen pounds.

Main.javajava
public class Main {
    public static void main(String[] args) {
        double savings = 100;
        int years = 0;
        while (savings < 200) {
            savings = savings * 1.10;
            years++;
        }
        System.out.printf("%d years, savings %.2f%n", years, savings);
    }
}
Output
8 years, savings 214.36

How while works

First, check the condition. If it's true, run the body. Then go back, and check again. Something inside the body must change, or the loop runs forever.

keyvalue
1check the condition
2true: run the body
3go back to 1
Mustchange something inside

Summary

A while loop repeats while its condition is true. Make sure something changes inside, so it can stop. Next, a loop that always runs at least once.

Key takeaways
  • while (condition)
  • Check, run, repeat
  • Change something
Next up: do while — run at least once