Java Loops
for Loop
Use a for loop when you know exactly how many times to iterate. It has three parts: initialization, condition, and update.
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.print(i + " "); // 1 2 3 4 5
}
System.out.println();
// while loop — condition checked before each iteration
System.out.println("--- while loop ---");
int n = 1;
while (n <= 5) {
System.out.print(n + " ");
n++;
}
System.out.println();
// do-while loop — body executes at least once
System.out.println("--- do-while loop ---");
int x = 1;
do {
System.out.print(x + " ");
x++;
} while (x <= 5);
System.out.println();
}
}
for-each Loop (Enhanced for)
The enhanced for loop iterates over arrays and collections without needing an index variable. It's cleaner and less error-prone.
public class ForEach {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// for-each loop
System.out.println("--- for-each ---");
for (int num : numbers) {
System.out.print(num + " "); // 10 20 30 40 50
}
System.out.println();
// break — exits the loop immediately
System.out.println("--- break ---");
for (int i = 1; i <= 10; i++) {
if (i == 6) break;
System.out.print(i + " "); // 1 2 3 4 5
}
System.out.println();
// continue — skips the current iteration
System.out.println("--- continue (skip evens) ---");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
System.out.print(i + " "); // 1 3 5 7 9
}
System.out.println();
}
}
Nested Loops
A loop inside another loop is called a nested loop. Commonly used for 2D data like matrices or multiplication tables.
public class NestedLoops {
public static void main(String[] args) {
// Print a 5x5 multiplication table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
/*
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
*/
}
}
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.