Loops
Java provides several kinds of loops: for, for-each (enhanced for), while, and do-while. Each kind has a specific use depending on the iteration needs.
The for loop is a good fit when the number of iterations is known upfront. The for-each loop is the most compact way to iterate over elements of an array or collection — no index needed. The while loop repeats as long as the condition is true, making it a good fit for iterations that depend on a runtime condition. do-while guarantees at least one execution before checking the condition, which is a good fit for input validation.
Java 5+ supports the enhanced for-each with the syntax for (Type element : array). The break operator stops the loop, and continue skips the current iteration and moves to the next one. Labels can be used to control nested loops.
Types of Loops:
- for — the number of iterations is known
- for-each — iterate over array/collection elements
- while — repeat while the condition is true
- do-while — at least one execution first
Code Example
public class Loops {
public static void main(String[] args) {
// For loop
System.out.println("=== For Loop ===");
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
// For-each loop
System.out.println("\n=== For-Each Loop ===");
String[] fruits = {"apple", "mango", "orange"};
for (String item : fruits) {
System.out.println("Fruit: " + item);
}
// While loop
System.out.println("\n=== While Loop ===");
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
// Do-while loop
System.out.println("\n=== Do-While Loop ===");
int number = 10;
do {
System.out.println("Number: " + number);
number++;
} while (number < 5); // still executes once even though the condition is false
}
}
Code Explanation
- For loop:
for (int i = 1; i <= 5; i++)— initializei=1, check the conditioni<=5, and incrementi++after each iteration. - For-each:
for (String item : fruits)— automatically takes each element of thefruitsarray and stores it in theitemvariable. - While loop: the loop continues as long as
count <= 5. Note thatcount++must be inside the loop to avoid an infinite loop. - Do-while: the code block runs first, and only then is the condition checked. Even though
number=10is already greater than 5, the first line still prints "Number: 10".
Everyday Example
A program that prints a multiplication table using a nested for loop:
public class MultiplicationTable {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
StringBuilder line = new StringBuilder();
for (int j = 1; j <= n; j++) {
line.append(String.format("%4d", i * j));
}
System.out.println("Multiplication " + i + ":" + line);
}
}
}
Summary
Loops enable repeated code execution efficiently. Pick the right kind of loop: for for counter-based iteration, for-each for arrays/collections, while for dynamic conditions, and do-while for input validation. Avoid infinite loops by making sure the terminating condition is eventually reached.