Loops in Java
Loops in Java are used to execute a block of code repeatedly until a specific condition is met. Java supports several types of loops:
1. while Loop
The while loop executes a block of code as long as a specified condition is true.
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count is: " + i);
i++;
}
}
}
2. do-while Loop
The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition.
public class Main {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Count is: " + i);
i++;
} while (i <= 5);
}
}
3. for Loop
The for loop is used when you know exactly how many times you want to execute a block of code.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
}
}
4. for-each Loop
The for-each loop is used to iterate through elements of an array or a collection.
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("Number is: " + number);
}
}
}
Loop Control Statements
Java provides loop control statements break and continue to control the execution flow of loops:
break Statement
The break statement terminates the loop and transfers control to the next statement outside the loop.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println("Count is: " + i);
}
}
}
continue Statement
The continue statement skips the current iteration of the loop and proceeds to the next iteration.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Count is: " + i);
}
}
}
Nested Loops
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.printf("(%d,%d) ", row, col);
}
System.out.println();
}
Watch total iterations — a double loop over 1000×1000 elements runs one million times.
Labeled break and continue
Break out of an outer loop from an inner loop:
outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (i * j > 50) break outer;
System.out.println(i * j);
}
}
Use labels sparingly — extracting a method is often clearer.
Choosing the Right Loop
| Loop | Best for |
|---|---|
for |
Known iteration count, index needed |
while |
Condition checked before each iteration |
do-while |
At least one execution guaranteed |
for-each |
Iterating collections or arrays |
Common Loop Patterns
// Sum array
int sum = 0;
for (int n : numbers) sum += n;
// Find first match
OptionalInt first = IntStream.of(numbers).filter(n -> n > 10).findFirst();
// Reverse iteration
for (int i = list.size() - 1; i >= 0; i--) {
process(list.get(i));
}
Infinite Loop Pitfalls
while (true) { /* server event loop — intentional */ }
while (count < 10) {
// forgot to increment count — infinite loop!
}
Always ensure the loop condition eventually becomes false (unless intentionally infinite).