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.
💡 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").
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.
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!
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 .
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.
In these cases, use a regular for loop instead.
Sometimes you need to exit a loop early or skip certain iterations. Java gives you two tools:
💡 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.
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.
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:
💡 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() .
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--.