🎯 What you will learn
Loops are how computers do repetitive work efficiently. A compound interest calculator that would take 100 lines without a loop takes 4 with one. Java has three loop constructs, each with a natural home:
| Loop | Best for | Key feature |
|---|---|---|
for | Known iteration count | Init, condition, update in one line |
for-each | Iterating arrays/collections | No index needed, cleaner syntax |
while | Unknown count, condition-driven | May execute 0 times |
do-while | Must execute at least once | Condition checked after body |
🔁 The for loop
Structure: for (initialisation; condition; update). All three parts are optional (omitting condition gives an infinite loop — useful with break). The loop variable (i, year) is local to the loop block.
⏳ while and do-while
while: checks the condition before each iteration — may run zero times. Use when you don't know how many iterations will happen (e.g., draining a payment queue until it's empty or funds run out).
do-while: checks the condition after — always runs at least once. Perfect for "show the prompt, then ask again if wrong" patterns like OTP entry.
🛒 Real-world scenario
Tunde is a backend engineer at NaijaCart in Lagos. The daily settlement job reads an array of transaction amounts. Negative values are reversals (skip them). The sentinel value -9999 marks the end of the day's feed — stop processing there. He uses break and continue to handle both cases cleanly.
🧩 Mini challenge
Print the first 10 Fibonacci numbers using a for loop: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Each number is the sum of the two before it. Use three variables: a, b, temp.
Given int n = 84521, reverse its digits using a while loop (extract the last digit with % 10, build the reversed number by multiplying by 10 and adding). Print 12548.
Print a 6-month EMI schedule for a ₹1,00,000 loan at 12% annual rate. Each row: month number, opening balance, interest, EMI (₹1,776.98), closing balance. Use a for loop and printf.
🎤 Interview Q&A
break exits the loop entirely — execution jumps to the statement after the closing brace. continue skips the rest of the current iteration and jumps to the loop's update expression (for) or condition check (while/do-while). Use break when you have found what you were looking for or hit a sentinel. Use continue to skip invalid or irrelevant entries without exiting the loop.
A while loop checks the condition before entering the body — if the condition is false from the start, the body never executes (zero iterations). A do-while executes the body first and checks the condition afterwards — it always runs at least once. Use do-while for input/retry scenarios where you must take the action before you know whether to repeat (e.g., OTP entry, menu display).
Use indexed for (int i = 0; i < arr.length; i++) when you need the index itself — to modify the array in place, access adjacent elements, iterate backwards, or track position. Use enhanced for-each (for (T item : collection)) when you only need each element's value — it's cleaner, avoids off-by-one errors, and works on any Iterable, not just arrays. You cannot modify the array through the for-each loop variable — it's a copy of the reference/value.
A loop becomes infinite when its exit condition is never met. Common causes: (1) forgetting to update the loop variable (while (i < 10) without i++); (2) updating the wrong variable; (3) floating-point comparison that never reaches exact equality (while (d != 1.0) — use < instead). To avoid: always trace the update path, add a maximum-iteration guard for safety-critical loops, and prefer for-each when you don't need explicit control.
Java allows labels on loops: outer: for (...) { inner: for (...) { break outer; } }. break outer exits the outer loop, not just the inner one. continue outer skips the rest of the outer body and moves to the outer loop's next iteration. This is useful in matrix search (stop all loops once the target is found) or multi-dimensional batch processing. Labelled breaks are rare in production code — if you need them often, consider refactoring the nested logic into a method with a regular return.
📝 Quiz — 5 questions
for (int i = 0; i < 5; i++) produce as final value of i after the loop?Next: methods and scope →
⚠️ Common mistakes
for (int i = 1; i <= arr.length; i++) causes ArrayIndexOutOfBoundsException on the last iteration — arrays are zero-indexed. Use i < arr.length. This is the #1 array bug in interviews.while (balance > 0) { balance += interest; } — adding to balance instead of subtracting means balance never reaches 0. Always trace the update path before running a while loop.ConcurrentModificationException. Use an explicit iterator with iterator.remove(), or collect items to remove and delete them after the loop.while (d != 0.0) may never exit due to floating-point precision errors. Use while (d > 0.001) with a small epsilon instead of exact equality checks on doubles.✅ Key takeaways
- Use
forwhen the iteration count is known;whilewhen driven by a condition;do-whilewhen at least one execution is required. - For-each (
for (T item : collection)) is cleaner than indexed for when you don't need the index. breakexits the entire loop;continueskips only the current iteration.- Arrays are zero-indexed — loop condition is
i < arr.length, noti <= arr.length. - Avoid floating-point equality in loop conditions — use a tolerance or counter instead.
- Label loops (
outer:) for clean multi-level break/continue in nested structures.
From loops to production Spring Boot
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →