Loops — for, while, do-while, for-each, break, continue, and Labeled Loops
In this tutorial, you will learn about Loops. We cover key concepts, practical examples, and best practices to help you master this topic.
Loops in Java execute a block of code repeatedly, with for, while, do-while, and for-each constructs providing different iteration strategies. Without loops, processing a list of a thousand items would require a thousand lines of code — loops let you write the logic once and let the machine handle repetition.
What You'll Learn
- When to use each loop type
- Infinite loops and how to avoid them
break,continue, and labeled loops for fine-grained control- The enhanced for-each loop for collections and arrays
Why It Matters
Choosing the wrong loop pattern leads to off-by-one errors, infinite loops, or unreadable code. The enhanced for-each loop, for example, is cleaner but cannot modify the collection during iteration — using it incorrectly causes ConcurrentModificationException.
Real-World Use
Loops Process data in every layer: a web server loops through request headers, a batch job loops through database records, and a game engine loops through the update cycle 60 times per second.
The for Loop
The classic for loop has three parts: initialization, condition, and update.
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Execution order:
int i = 0runs once before the loopi < 5is evaluated before each iteration — if false, the loop exits- The body executes
i++runs after the body- Repeat from step 2
Multiple Variables
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i=" + i + ", j=" + j);
}
Off-by-One Errors
// Common bug: using <= instead of <
for (int i = 0; i <= 5; i++) { // runs 6 times (0-5)
// ...
}
The while Loop
Use while when the number of iterations is not known in advance:
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
System.out.print("Enter a command: ");
input = scanner.nextLine();
System.out.println("You entered: " + input);
}
The condition is checked before each iteration. If it is initially false, the body never executes.
Infinite Loops
// Bug: condition never becomes false
int x = 0;
while (x < 10) {
// forgot to increment x
}
Always ensure the loop variable is updated toward the termination condition.
The do-while Loop
do-while guarantees the body executes at least once:
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
This is useful for menu-driven programs where you want to show the menu at least once before checking for exit.
The Enhanced for-each Loop
The for-each loop iterates over arrays and collections without an explicit index:
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Output:
Apple
Banana
Cherry
With Collections
List<Integer> numbers = List.of(10, 20, 30);
for (int n : numbers) {
System.out.println(n * 2);
}
Limitation: Cannot Modify the Collection
The for-each loop uses an internal Iterator. If you modify the collection during iteration (adding or removing elements), you get a ConcurrentModificationException:
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
for (String s : list) {
if (s.equals("b")) {
list.remove(s); // throws ConcurrentModificationException
}
}
Use an explicit Iterator or removeIf() for structural modification.
break and continue
break
break exits the loop immediately:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // loop stops when i is 5
}
System.out.print(i + " ");
}
// Output: 0 1 2 3 4
continue
continue skips the rest of the current iteration and proceeds to the next:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
System.out.print(i + " ");
}
// Output: 1 3 5 7 9
Labeled Loops
Labels allow break and continue to target an outer loop from within nested loops:
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break outer; // exits both loops
}
System.out.println("i=" + i + ", j=" + j);
}
}
Output:
i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
Without the label, break would only exit the inner loop. Labels make the intent explicit, though some developers prefer extracting the nested loop into a method with a return statement.
Loop Comparison
| Loop Type | When to Use |
|---|---|
for |
Known number of iterations |
while |
Unknown iterations, condition before body |
do-while |
At least one iteration required |
Enhanced for |
Iterating over arrays/collections without index manipulation |
Common Mistakes
- Off-by-one errors with
<=instead of<.for (int i = 0; i <= array.length; i++)causesArrayIndexOutOfBoundsException. - Modifying a collection during for-each iteration. Use
Iterator.remove()or collect removals in a separate list. - Using
continuein awhileloop without updating the loop variable. This creates an infinite loop because the increment is skipped. - Forgetting to advance the Scanner in a while loop.
while (scanner.hasNext())without callingnext()loops forever. - Using
==for string comparison in loop conditions.while (!input.equals("quit"))is correct;while (input != "quit")compares references.
Practice Questions
1. What is the output of this code?
int i = 0;
while (i < 3) {
System.out.print(i + " ");
i++;
}
0 1 2
2. How does break differ from continue?
break exits the loop entirely. continue skips the current iteration and moves to the next.
3. Why does modifying a List during for-each iteration throw an exception?
The for-each loop uses an internal iterator that checks for structural modification via a modCount field. Any change increments the count, and the iterator throws ConcurrentModificationException when it detects the change.
4. What is the difference between while and do-while?
while checks the condition before executing the body (zero or more iterations). do-while checks after (one or more iterations).
5. What does break outer do in nested loops?
It exits the loop labeled outer, which can be the outer of multiple nested loops. Without the label, break only exits the innermost loop.
Challenge Question:
Write a program that prints a multiplication table (1-12) using nested loops. Use the \t tab character for alignment. Then use a labeled continue to skip printing any row or column where the product is a multiple of 5.
FAQ
Mini Project
Write a program PrimeFinder.java that:
- Uses nested loops to find and print all prime numbers between 2 and 100
- The outer loop iterates through candidate numbers
- The inner loop checks divisibility by numbers from 2 to sqrt(candidate)
- Uses labeled
continueorbreakto skip non-primes - Prints the result in the format:
Prime numbers: 2, 3, 5, 7, 11, ...
Then extend it to accept an upper limit from command-line arguments. Finally, rewrite the inner loop as a separate method isPrime(int n).
What's Next
Now that you can repeat operations, you need data structures to hold collections of values. Lesson 8 introduces arrays — the most fundamental data structure in Java — including declaration, initialization, multi-dimensional arrays, and the Arrays utility class for sorting, searching, and filling.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro