Java
Beginner
1 min read
for, while, do-while, and the Enhanced for Loop
Example
import java.util.List;
public class LoopsDemo {
public static void main(String[] args) {
// --- Traditional for loop ---
System.out.print("Squares: ");
for (int i = 1; i <= 8; i++) {
System.out.print(i * i + " ");
}
System.out.println();
// --- While loop: read until condition ---
int n = 1;
System.out.print("Powers of 2 below 1000: ");
while (n < 1000) {
System.out.print(n + " ");
n *= 2;
}
System.out.println();
// --- Do-while: body runs at least once ---
int counter = 0;
do {
System.out.println("do-while iteration: " + counter);
counter++;
} while (counter < 3);
// --- Enhanced for over an array ---
int[] primes = {2, 3, 5, 7, 11, 13};
int sum = 0;
for (int prime : primes) {
sum += prime;
}
System.out.println("Sum of primes: " + sum);
// --- Enhanced for over a List ---
List<String> langs = List.of("Java", "Python", "Kotlin", "Go");
for (String lang : langs) {
System.out.println("Language: " + lang);
}
// --- break and continue with label ---
outer:
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
if (col == 2) continue outer; // skip rest of inner, advance row
if (row == 3) break outer; // exit both loops
System.out.printf("(%d,%d) ", row, col);
}
}
System.out.println("\nDone.");
}
}