Loops
Imagine you need to print "Hello" 1,000 times, or add up every number in a list, or check every word in a document for spelling errors. You can't write 1,000 lines of code for that! Loops let you repeat a block of code as many times as you need — they're one of the most powerful concepts in all of programming.
Learn Loops in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
- ✅ for loops — when you know exactly how many times to repeat
- ✅ while loops — when you don't know when to stop
- ✅ do-while loops — guaranteed to run at least once
- ✅ Enhanced for-each loops — the easiest way to iterate over arrays
- ✅ break and continue — controlling loop flow
- ✅ Nested loops — loops inside loops (multiplication tables, patterns)
- ✅ How to avoid the dreaded infinite loop
💡 Real-World Analogy
A loop is like a washing machine cycle. You set the conditions ("wash for 30 minutes" or "until the clothes are clean"), and the machine repeats the same actions (agitate, rinse) until the condition is met. A for loop is like a timed cycle ("run 10 times"). A while loop is like a sensor-based cycle ("keep going until clean").
1️⃣ The For Loop — "Repeat Exactly N Times"
The for loop is the most common loop in Java. Use it when you know how many times you want to repeat. It packs three things into one line: where to start, when to stop, and how to count.
- int i = 0 — create the counter (runs once)
- i < 5 → true → run the body → print "i = 0"
- i++ → i becomes 1
- i < 5 → true → run the body → print "i = 1"
- ...continues until i reaches 5
- 5 < 5 → false → loop ends
2️⃣ The While Loop — "Keep Going Until..."
The while loop checks its condition before each iteration. If the condition is false from the start, the body never runs at all. Use it when you don't know in advance how many iterations you need.
Common use case: Reading user input until they type "quit":
⚠️ Critical: The condition variable ( power , input ) must change inside the loop. If it never changes, the condition never becomes false, and you get an infinite loop — your program freezes!
3️⃣ Do-While — "Do It At Least Once"
The do-while loop is like a while loop, but it checks the condition after running the body. This means the body always runs at least once , even if the condition is false. It's perfect for menu systems and input validation.
🔑 while vs do-while: If the user might not need to see the prompt at all, use while . If you always want to show it at least once (menus, prompts), use do-while .
4️⃣ Enhanced For-Each — "For Every Item In..."
When you want to go through every item in an array or collection, the for-each loop is the cleanest option. No counter variable, no index, no chance of an off-by-one error.
- When you need the index (e.g., "item 3 of 10")
- When you need to modify the array while looping
- When you need to loop backwards
In these cases, use a regular for loop instead.
5️⃣ Break & Continue — Loop Flow Control
Sometimes you need to exit a loop early or skip certain iterations. Java gives you two tools:
break — "Stop the loop NOW"
continue — "Skip this one"
💡 Use sparingly: Too many break and continue statements make code hard to follow. Often you can restructure your condition instead. But for search operations, break is perfectly natural.
6️⃣ Nested Loops — Loops Inside Loops
You can put a loop inside another loop. The inner loop runs completely for each iteration of the outer loop. If the outer loop runs 3 times and the inner loop runs 4 times, the body runs 3 × 4 = 12 times total.
Common uses: 2D grids (game boards, images), generating tables, comparing every pair of items, building patterns.
7️⃣ The Infinite Loop — And How to Avoid It
An infinite loop is a loop that never stops. Your program freezes, your CPU spins at 100%, and nothing else can happen. It's the most common loop bug:
🛟 If your program is stuck in an infinite loop:
- In terminal: Press Ctrl + C to force-stop
- In IDE: Click the red "Stop" button
- To prevent: Always verify your loop variable changes in the right direction
8️⃣ Which Loop Should I Use?
Question
Answer
Use
Do you know how many times?
Yes
for
No
while
Must it run at least once?
do-while
Iterating an array/list?
Yes, all items
for-each
Common Mistakes
- ❌ Infinite loop — forgetting to update the counter:
- ❌ Off-by-one error: Using <= when you meant < , or starting at 1 instead of 0. Arrays start at index 0!
- ❌ Modifying a collection during for-each: You cannot add/remove items from an ArrayList while iterating with for-each. Use an Iterator or collect changes separately.
- ❌ Wrong loop variable in nested loops: Using i in both outer and inner loop causes shadowing bugs. Use different names like i and j .
Pro Tips
💡 Prefer for-each when possible — it's cleaner and prevents index errors. Only use a regular for loop when you need the index.
💡 Use meaningful variable names — for (String student : students) is much clearer than for (String s : arr) .
💡 Extract loop bodies into methods — if the loop body is more than 5-10 lines, pull it into a separate method for readability.
💡 Consider Stream API later — once you learn Streams (Lesson 27), you'll often replace loops with .filter() , .map() , and .collect() .
📋 Quick Reference
Loop
Syntax
Best For
for (init; cond; update)
Known iteration count
while (condition)
Unknown count, check first
do { } while (cond);
Must run at least once
for (T item : collection)
Iterate all items in array/list
break
break;
Exit loop immediately
continue
continue;
Skip to next iteration
🎉 Lesson Complete!
You've mastered all four types of Java loops, plus break and continue for flow control! You can now automate repetitive tasks, process arrays, build patterns, and even solve FizzBuzz — a classic coding interview question.
Next up: Methods — write reusable code blocks with parameters and return values to organize your programs into clean, testable pieces.
Practice quiz
Which loop is best when you know exactly how many times to repeat?
- while
- do-while
- for
- if
Answer: for. A for loop packs start, condition, and update into one line — ideal for a known count.
How many times does 'for (int i = 0; i < 5; i++)' run its body?
- 4
- 5
- 6
- Infinite
Answer: 5. i goes 0,1,2,3,4 — that is 5 iterations; it stops when i reaches 5.
What makes a do-while loop different from a while loop?
- It never stops
- Its body always runs at least once
- It cannot use a condition
- It only works with arrays
Answer: Its body always runs at least once. do-while checks the condition AFTER the body, so the body always runs at least once.
What does the break statement do inside a loop?
- Skips the current iteration
- Exits the loop immediately
- Restarts the loop
- Pauses for a second
Answer: Exits the loop immediately. break exits the loop immediately; continue is what skips to the next iteration.
What does continue do inside a loop?
- Exits the loop
- Skips the rest of this iteration and moves to the next
- Ends the program
- Doubles the counter
Answer: Skips the rest of this iteration and moves to the next. continue skips the remaining body for this iteration and proceeds to the next one.
If an outer loop runs 3 times and an inner loop runs 4 times, how many times does the inner body run total?
- 7
- 12
- 3
- 4
Answer: 12. Nested loops multiply: 3 × 4 = 12 total executions of the inner body.
What is the most common cause of an infinite while loop?
- Using a for-each
- The condition variable never changes
- Using break
- Declaring too many variables
Answer: The condition variable never changes. If the variable in the condition never changes, the condition stays true forever — an infinite loop.
Which loop is cleanest for reading every element of an array without an index?
- do-while
- while
- for-each (enhanced for)
- switch
Answer: for-each (enhanced for). The for-each loop iterates every element with no counter or index, avoiding off-by-one bugs.
In the lesson, 'while (power <= 1000) power *= 2;' starting at power = 1 ends with power equal to what?
- 512
- 1000
- 1024
- 2048
Answer: 1024. Doubling 1 ten times reaches 1024, the first power of 2 greater than 1000.
Why is 'for (int i = 10; i >= 0; i++)' a bug?
- i++ moves i away from the stop condition, looping forever
- You cannot start at 10
- i >= 0 is invalid
- It runs exactly once
Answer: i++ moves i away from the stop condition, looping forever. Counting up (i++) while the condition checks i >= 0 never becomes false — it should be i--.
Continue this course
- Previous: Previous Lesson
- Next: Next Lesson