Control flow

Core Java · lesson 3 of 42 · 3 min read

Branch with if, repeat with the four loop forms, and pick the right one each time.

Open this lesson in the learning hub

Key points

  • if needs a real boolean. Java has no truthiness, so if (list) will not compile.
  • Use the enhanced for (for (int s : scores)) whenever you do not need the index.
  • Use the classic for when you need the index or a custom step, and while when the number of rounds is unknown.
  • break leaves the loop; continue jumps to the next round.
  • do-while runs 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.