Loops
Loops in Java
Java provides four loop constructs to repeat blocks of code.
for loop Best when the number of iterations is known. Consists of an initializer, condition, and update:
for (int i = 0; i < 10; i++) { … }while loop Checks the condition before each iteration. Use when iterations are unknown:
while (input != null) { … }do-while loop Executes the body at least once, then checks the condition:
do { … } while (condition);for-each (enhanced for) loop
Iterates over arrays and Iterable collections without an index:
for (String item : items) { … }break and continue
breakexits the nearest enclosing loop immediately.continueskips the remainder of the current iteration and moves to the next.
Key points:
- Prefer the for-each loop when you don't need the index — it is less error-prone.
- Avoid modifying a collection while iterating it with for-each (use an Iterator instead).
- Label + break can exit nested loops:
outer: for(…) { … break outer; }.
Code Examples
public class Loops {
public static void main(String[] args) {
// for loop
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println("Sum 1-5: " + sum);
// while loop
int n = 1;
while (n < 32) {
n *= 2;
}
System.out.println("First power of 2 >= 32: " + n);
// do-while
int count = 0;
do {
count++;
} while (count < 3);
System.out.println("Count: " + count);
}
}do-while always executes the body at least once. The while loop may never execute if the condition is false initially.
public class ForEachDemo {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "cherry", "date", "elderberry"};
// for-each with continue
System.out.println("Fruits not starting with 'b':");
for (String fruit : fruits) {
if (fruit.startsWith("b")) continue;
System.out.println(" " + fruit);
}
// for with break
System.out.println("First fruit longer than 5 chars:");
for (String fruit : fruits) {
if (fruit.length() > 5) {
System.out.println(" " + fruit);
break;
}
}
}
}continue skips the current iteration; break exits the loop entirely. for-each is idiomatic for array/collection traversal.
Quick Quiz
1. Which loop always executes its body at least once?
2. What does `continue` do inside a loop?
Was this lesson helpful?