Control flow
Branch with if, repeat with the four loop forms, and pick the right one each time.
Open this lesson in the learning hubKey points
ifneeds a realboolean. Java has no truthiness, soif (list)will not compile.- Use the enhanced for (
for (int s : scores)) whenever you do not need the index. - Use the classic
forwhen you need the index or a custom step, andwhilewhen the number of rounds is unknown. breakleaves the loop;continuejumps to the next round.do-whileruns the body once before it checks the condition.- Always use braces. Brace-less one-line
ifs are where bugs hide.
Example
public class Main {
public static void main(String[] args) {
int[] scores = {88, 45, 72, 95, 60};
int passed = 0;
for (int s : scores) {
if (s >= 60) {
passed++;
}
}
System.out.println(passed + " of " + scores.length + " passed");
for (int i = 1; i <= 6; i++) {
if (i % 2 == 0) continue;
if (i == 5) break;
System.out.println("odd below five: " + i);
}
int n = 27, steps = 0;
while (n != 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
System.out.println("27 reaches 1 in " + steps + " steps");
int tries = 0;
do {
tries++;
} while (tries < 3);
System.out.println("do-while always runs once: tries = " + tries);
}
}
Enhanced for by default; the classic for only when you need the index.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.