Loops
Loops repeat work — for every item in a list, until a condition changes, or a fixed number of times.
On this page · 5 min · Beginner
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 30, 2026
Related tutorials
In simple words#
A loop is a teacher calling roll: repeat “say the next name” for every student on the register, and stop when the list ends.
- for
- Counter-based loop.
- for-each
- Visit every element of an array or collection.
- while / do-while
- Repeat while a condition holds (do-while runs at least once).
Learning objectives#
- Write counter loops
- Iterate collections with for-each
- Use while and do-while
- Control loops with break and continue
Explanation#
for (int i = 0; i < n; i++) — when you need the index.
for (Type item : collection) — simplest way to visit every element.
while (condition) checks before each run; do { } while (condition) runs at least once.
break exits the loop; continue skips to the next iteration.
Code example: Totals, skipping and searching#
int[] prices = {499, 1299, 0, 250, 899};
int total = 0;
for (int price : prices) {
if (price == 0) continue; // skip free items
total += price;
}
System.out.println("Total: ₹" + total);
for (int i = 0; i < prices.length; i++) {
if (prices[i] > 1000) {
System.out.println("First expensive item at index " + i);
break;
}
}
int attempts = 0;
do {
attempts++;
} while (attempts < 3);
System.out.println("Attempts: " + attempts);
Total: ₹2947 First expensive item at index 1 Attempts: 3
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- for-each adds every non-zero price.
- continue skips the free item.
- The indexed loop stops at the first price above 1000.
- do-while runs before checking the condition.
Real-world use case#
Batch jobs loop over thousands of orders to calculate totals and send invoices.
Common mistakes#
Use i < length, not i <= length, to avoid ArrayIndexOutOfBoundsException.
Make sure the condition eventually becomes false.
Best practices#
- Prefer for-each when the index isn’t needed
- Keep loop bodies short
- Consider streams for transformations
- Avoid modifying a list while iterating it
Remember this#
for = index, for-each = items, while = condition.
break exits, continue skips.
i < length, not <=.
Practice exercise#
Your task: Print the multiplication table of 7 from 1 to 10.
Show solution
for (int i = 1; i <= 10; i++) {
System.out.println("7 x " + i + " = " + (7 * i));
}
Mini quiz#
Which loop always runs its body at least once?
Want more? Practise all Java MCQs · Java interview questions
My notes#
Saved in this browser.