Java Tutorial · Control Flow · Lesson 15 of 37
Java Loops
while, do-while, for and for-each loops, with break and continue.
while and do-while
public class Main {
public static void main(String[] args) {
int n = 1;
while (n < 50) {
n *= 2;
}
System.out.println(n);
int tries = 0;
do {
tries++;
} while (tries < 0);
System.out.println("ran " + tries + " time(s)");
}
}
Output
64 ran 1 time(s)
Run this on your computer — see “Get Started” for setup.
for
The classic for loop has an initialiser, a condition and an update:
public class Main {
public static void main(String[] args) {
for (int i = 5; i > 0; i--) {
System.out.print(i + " ");
}
System.out.println("liftoff!");
}
}
Output
5 4 3 2 1 liftoff!
Run this on your computer — see “Get Started” for setup.
for-each
The enhanced for loop iterates over arrays and collections — use it whenever you don't need the index:
public class Main {
public static void main(String[] args) {
String[] langs = {"Java", "Kotlin", "Scala"};
for (String lang : langs) {
System.out.println(lang + " runs on the JVM");
}
int total = 0;
for (int x : new int[]{3, 5, 7}) total += x;
System.out.println(total);
}
}
Output
Java runs on the JVM Kotlin runs on the JVM Scala runs on the JVM 15
Run this on your computer — see “Get Started” for setup.
break, continue and labels
break leaves the loop; continue jumps to the next iteration. A label lets you break out of an outer loop:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue;
if (i > 7) break;
System.out.print(i + " ");
}
System.out.println();
outer:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
if (row * col == 4) {
System.out.println("found 4 at " + row + "," + col);
break outer;
}
}
}
}
}
Output
1 2 4 5 7 found 4 at 2,2
Run this on your computer — see “Get Started” for setup.
Test yourself
Which loop is best for visiting every element of a list when you don't need the index?
whiledo-whilefor-eachswitch
Show answer
Answer: for-each