Java Loops
Loops repeat a block of code while a condition is true.
| Loop | Use when | Checks condition |
|---|---|---|
| for | Number of iterations is known | Before each iteration |
| while | Iterations are not known in advance | Before each iteration |
| do-while | Body must run at least once | After each iteration |
for Loop
for (int i = 1; i <= 5; i++) {
System.out.println("5 x " + i + " = " + (5 * i));
}
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
while Loop
int num = 1234, sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of digits: " + sum);
Sum of digits: 10
do-while Loop
int i = 10;
do {
System.out.println("i = " + i);
i++;
} while (i < 5); // body still ran once
i = 10
for-each Loop
String[] langs = {"Java", "Python", "C"};
for (String s : langs) {
System.out.print(s + " ");
}
Java Python C
Quick Check
Which loop always executes its body at least once?
Track your progress through the Java course