Java Loops

Loops repeat a block of code while a condition is true.

LoopUse whenChecks condition
forNumber of iterations is knownBefore each iteration
whileIterations are not known in advanceBefore each iteration
do-whileBody must run at least onceAfter each iteration

for Loop

Java
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

Java
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

Java
int i = 10;
do {
    System.out.println("i = " + i);
    i++;
} while (i < 5);   // body still ran once
i = 10

for-each Loop

Java
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