4.1 The while Loop
The while Loop in Java
Unit 4: Loops and Collections of Actors · Lesson 4.1 · about 30 minutes · no coding experience needed
In Unit 1 you were told a loop inside act() freezes Greenfoot. Now you are going to write loops. Those are not contradictory, and the difference between them is the most important thing in this lesson.
What you will be able to do
- Write a while loop that runs a known number of times
- Explain why a loop inside act() is safe when it finishes
- Identify the missing line that turns a loop infinite
Words you will need
- Loop
- In plain words Code that repeats.
- More precisely A control structure that executes its body repeatedly while a condition holds.
- Iteration
- In plain words One pass through the loop body.
- More precisely A single execution of the loop body.
- Infinite loop
- In plain words A loop whose condition never becomes false.
- More precisely A loop with no path to termination.
Build it step by step
Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.
-
Step 1
On your screen A while loop in an editor with the condition and body labeled, and the counter increment highlighted.
int count = 0; while (count < 5) { addObject(new Coin(), count, 0); count = count + 1; }Three parts, and all three are required.
A starting value: `int count = 0;` A condition: `count < 5`, checked BEFORE each pass. A change: `count = count + 1;`, which moves the condition toward false.
This places five coins, at x values 0, 1, 2, 3 and 4. Note it stops at 4, not 5, because the check happens first and 5 < 5 is false.
-
Step 2
On your screen The same loop with the increment line deleted and Greenfoot frozen.
// FREEZES. count never changes, so count < 5 is true forever. int count = 0; while (count < 5) { addObject(new Coin(), count, 0); }Delete one line and the scenario locks up completely.
count starts at 0 and nothing ever changes it, so `count < 5` is true on every check, forever. Greenfoot never regains control and the window stops responding.
When a loop hangs, look for the line that should be moving the condition. It is nearly always missing rather than wrong.
-
Step 3
On your screen A diagram contrasting a finishing loop inside act with a forever loop inside act.
// FINE. Runs 5 times, then act() returns. public void act() { int i = 0; while (i < 5) { i = i + 1; } move(1); }And here is the reconciliation with Unit 1.
A loop inside act() is completely fine PROVIDED IT FINISHES. This one runs five times, stops, and act() returns normally. Greenfoot draws the next frame and everything is well.
What 1.6 warned about was `while (true)`, which never returns. The problem was never loops. The problem was act() not finishing.
-
Step 4
On your screen A loop whose condition is false at the start, with the body never executing.
int lives = 0; while (lives > 0) { // never runs lives = lives - 1; }A while loop can run ZERO times. The condition is checked before the first pass, and if it is already false the body is skipped entirely.
That is usually what you want, and it is worth knowing so a loop that "did nothing" is not automatically assumed broken.
Mistakes almost everyone makes here
These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.
Common wrong idea Loops are banned inside act().
What is actually true A loop that FINISHES is fine. Only a loop that never ends is a problem.
Why it matters Unit 1 warned about while (true), and students often generalise that into a rule that would make this whole unit impossible.
Common wrong idea A while loop always runs at least once.
What is actually true It can run zero times, because the condition is checked first.
Why it matters Expecting a guaranteed first pass produces bugs that only appear at the boundary.
Common wrong idea `while (count < 5)` runs with count equal to 5 on the last pass.
What is actually true The last pass has count equal to 4. The check happens before the body.
Why it matters This off-by-one is the same one that governs arrays in Unit 5.
Common wrong idea An infinite loop is a syntax mistake Java will catch.
What is actually true It compiles perfectly. Java has no idea your condition can never become false.
Why it matters Students wait for an error that will never come while the window is already frozen.
Check your understanding
Answer these before moving on. They are graded instantly and you can retry.
-
1. How many times does this run? int i = 0; while (i < 3) { i = i + 1; }
-
2. What is missing here? int i = 0; while (i < 3) { move(1); }
-
3. Is a loop inside act() allowed?
-
4. int n = 0; while (n > 0) { n = n - 1; } How many times does the body run?
Fill in the code
Place four walls in a row along the top of the world, at x values 0, 1, 2 and 3. Fill in the three parts every loop needs.
int i = ;
while (i 4)
{
addObject(new Wall(), i, 0);
i = i 1;
}
Stuck? Open a hint for each blank
- Blank 1: The first x value you want a wall at.
- Blank 2: Keep going while i has not yet reached 4. One character.
- Blank 3: Move the counter toward the end.
Lesson quiz
This one counts toward your progress. Take it when the section above makes sense.
-
1. A while loop checks its condition:
-
2. Which of these freezes Greenfoot?
-
3. After `int i = 0; while (i < 4) { i = i + 1; }`, what is i?
-
4. Why does an infinite loop inside act() lock up the window?
The short version
- A loop needs a start, a condition, and something that changes the condition.
- The condition is checked BEFORE each pass, so a while loop can run zero times.
- A loop inside act() is fine as long as it finishes.
- An infinite loop compiles perfectly. Java cannot warn you.
If you get stuck
These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]