Control Flow in Java

Control flow statements decide which code runs and how often: if and switch choose between paths, loops repeat, and break, continue and return jump. Java's switch in particular has changed more than any other statement, from C-style fall-through to expressions and pattern matching. This page explains each construct, runs examples of every form, and shows the loop and branching mistakes that compile without complaint.

Contents

The building blocks

A Java method runs its statements top to bottom unless a control flow statement changes the order. There are three groups:

Control flow constructs
GroupConstructsUse for
Decisionsif / else, the ternary ? :, switchChoosing one path out of several
Loopsfor, enhanced for (for-each), while, do-whileRepeating work
Jumpsbreak, continue, return, yield, throwLeaving a loop, switch or method early

Two rules shape all of them. Conditions must be boolean: unlike C, if (count) with an int does not compile, which removes a whole class of bugs such as if (x = 5). And some constructs are statements (they do something) while others are expressions (they produce a value): if is a statement, the ternary operator is an expression, and switch can be either since Java 14.

if, else and the ternary operator

The program grades four scores, one per branch, picks a stock label with nested ternaries, shows why && makes null checks safe, and then runs a piece of code whose indentation lies about its meaning.

Java
public class IfAndConditions {

    static String grade(int score) {
        if (score >= 90) {
            return "A";
        } else if (score >= 80) {
            return "B";
        } else if (score >= 70) {
            return "C";
        } else {
            return "F";
        }
    }

    static int checks;

    static boolean expensive(boolean answer) {
        checks++;
        return answer;
    }

    public static void main(String[] args) {
        for (int s : new int[] {95, 85, 72, 40}) {
            System.out.print(s + "=" + grade(s) + " ");
        }
        System.out.println();

        // The ternary operator is an expression: it produces a value
        int stock = 3;
        String label = stock == 0 ? "sold out" : stock < 5 ? "few left" : "in stock";
        System.out.println("stock 3: " + label);

        // && and || skip the right side when the left side decides the result
        String name = null;
        if (name != null && name.length() > 3) {
            System.out.println("long name");
        } else {
            System.out.println("null-safe check passed without NullPointerException");
        }
        checks = 0;
        boolean result = expensive(true) || expensive(false);
        System.out.println("true || x evaluated " + checks + " operand(s), result " + result);

        // A dangling else belongs to the nearest if, whatever the indentation says
        int a = 5;
        int b = -1;
        String outcome = "unset";
        if (a > 0)
            if (b > 0)
                outcome = "both positive";
        else
            outcome = "a is not positive?";
        System.out.println("a=5, b=-1 gives: " + outcome);
    }
}

Output:

Output
95=A 85=B 72=C 40=F 
stock 3: few left
null-safe check passed without NullPointerException
true || x evaluated 1 operand(s), result true
a=5, b=-1 gives: a is not positive?
  • An if / else if chain tests conditions in order and runs the first branch that matches, so the order matters: 95 is also at least 80, but the >= 90 test comes first.
  • The ternary condition ? a : b is an expression, so it can be assigned or returned directly. Nesting works, as with the stock label, but more than two levels is hard to read; use if or a switch expression instead.
  • && and || evaluate the right side only if needed. name != null && name.length() > 3 never calls length() on null, and true || x evaluated just 1 operand. The single & and | always evaluate both sides (see bitwise operators).
  • The last example printed "a is not positive?" although a is 5. An else always belongs to the nearest if without one, here if (b > 0), whatever the indentation suggests. This "dangling else" is why style guides require braces on every branch.

switch: from statement to pattern matching

switch has gained a new form in several Java releases. The program shows each one: the classic statement and its fall-through, the switch expression with arrows, an exhaustive switch over an enum using yield, and pattern matching with types, guards and null.

Java
import java.time.DayOfWeek;

public class SwitchForms {

    // 1. The classic switch statement: cases fall through without break
    static int daysOld(int month) {
        int days;
        switch (month) {
            case 2:
                days = 28;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            default:
                days = 31;
        }
        return days;
    }

    // 2. A switch expression (Java 14): arrows, several labels, a value, no fall-through
    static int days(int month) {
        return switch (month) {
            case 2 -> 28;
            case 4, 6, 9, 11 -> 30;
            default -> 31;
        };
    }

    // 3. Over an enum, every constant handled: no default needed, and yield for blocks
    static String kind(DayOfWeek day) {
        return switch (day) {
            case SATURDAY, SUNDAY -> "weekend";
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> {
                String note = day == DayOfWeek.FRIDAY ? " (almost weekend)" : "";
                yield "weekday" + note;
            }
        };
    }

    // 4. Pattern matching (Java 21): types, guards and null
    static String describe(Object o) {
        return switch (o) {
            case null -> "nothing";
            case Integer i when i > 1000 -> "big number";
            case Integer i -> "number " + i;
            case String s -> "text of length " + s.length();
            default -> "other: " + o.getClass().getSimpleName();
        };
    }

    // A forgotten break falls into the next case (-Xlint:fallthrough warns about it)
    @SuppressWarnings("fallthrough")
    static String fallThrough(int level) {
        StringBuilder sb = new StringBuilder();
        switch (level) {
            case 1:
                sb.append("one ");
            case 2:
                sb.append("two ");
            default:
                sb.append("default");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println("Feb " + daysOld(2) + "/" + days(2) + ", Apr " + daysOld(4) + "/"
                + days(4) + ", Jul " + daysOld(7) + "/" + days(7));
        System.out.println("level 1 without break: " + fallThrough(1));
        System.out.println("FRIDAY: " + kind(DayOfWeek.FRIDAY)
                + ", SUNDAY: " + kind(DayOfWeek.SUNDAY));
        System.out.println(describe(5000) + ", " + describe(7) + ", " + describe("hey") + ", "
                + describe(null) + ", " + describe(2.5));

        // Switch on a String is case-sensitive, and an old-style switch on null throws
        String command = null;
        try {
            switch (command) {
                case "start" -> System.out.println("starting");
                default -> System.out.println("unknown");
            }
        } catch (NullPointerException e) {
            System.out.println("switch on a null String without case null: NullPointerException");
        }
    }
}

Output:

Output
Feb 28/28, Apr 30/30, Jul 31/31
level 1 without break: one two default
FRIDAY: weekday (almost weekend), SUNDAY: weekend
big number, number 7, text of length 3, nothing, other: Double
switch on a null String without case null: NullPointerException
  • In the classic form, execution starts at the matching case and continues into the next ones until a break. Several empty cases in a row (case 4: case 6: ...) share code this way. Forgetting a break does the same thing by accident: level 1 printed "one two default". javac warns about it with -Xlint:fallthrough.
  • The arrow form (case 4, 6, 9, 11 -> 30) never falls through and can list several labels in one case. As an expression it must produce a value for every input, so a default is required for an int.
  • Over an enum, a switch expression that handles every constant needs no default. If a constant is added to the enum later, the switch stops compiling instead of silently doing nothing. A case whose result needs several statements uses a block with yield.
  • Pattern matching (Java 21) switches on the type: case Integer i matches and casts in one step, when adds a condition, and the more specific when i > 1000 case must come first. case null handles null explicitly; see pattern matching for switch.
  • A switch without case null throws NullPointerException when given null, in every form. String cases are compared with equals, so they are case-sensitive.
switch features by Java version
JavaFeature
5Enums in case labels
7Strings in case labels
14Switch expressions, arrow labels, several labels per case, yield (JEP 361)
21Type patterns, when guards, case null, record patterns (JEP 441, JEP 440)

For more, see switch expressions.

The four loops, break, continue and labels

The program uses each loop where it fits best. The while loop computes the Collatz sequence from 27, a classic example of a loop whose number of steps cannot be known in advance; 27 was chosen because it takes a surprisingly long path.

Java
public class Loops {

    public static void main(String[] args) {
        // for: when you know how many times
        for (int i = 1; i <= 3; i++) {
            System.out.print("for " + i + "  ");
        }
        System.out.println();

        // while: test first, may run zero times
        int n = 27;
        int steps = 0;
        while (n != 1) {                       // Collatz sequence
            n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
            steps++;
        }
        System.out.println("27 reaches 1 after " + steps + " steps");

        // do-while: body runs at least once
        int tries = 0;
        do {
            tries++;
        } while (tries < 0);
        System.out.println("do-while ran " + tries + " time; its condition was false");

        // break and continue
        for (int i = 1; i <= 10; i++) {
            if (i % 3 == 0) {
                continue;                      // skip multiples of 3
            }
            if (i > 7) {
                break;                         // stop the loop entirely
            }
            System.out.print(i + " ");
        }
        System.out.println();

        // A labeled break leaves both loops at once
        int[][] grid = {
            {1, 2, 3},
            {4, 42, 6},
            {7, 8, 9}
        };
        search:
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] == 42) {
                    System.out.println("found 42 at row " + r + ", column " + c);
                    break search;
                }
            }
        }
    }
}

Output:

Output
for 1  for 2  for 3  
27 reaches 1 after 111 steps
do-while ran 1 time; its condition was false
1 2 4 5 7 
found 42 at row 1, column 1
  • for fits a known number of iterations: initialization, condition and update are in one line.
  • while tests first and may run zero times. Starting from 27, the Collatz rule (halve even numbers, otherwise triple and add one) took 111 steps to reach 1.
  • do-while tests after the body, so it ran once even though its condition was false from the start. It suits "do something, then check whether to repeat", such as prompting until the input is valid.
  • continue skipped 3 and 6; break ended the loop at 8, so 9 and 10 were never reached.
  • A plain break leaves only the innermost loop. break search left both loops as soon as 42 was found. Labels are rarely needed, and often a separate method with return reads better.
Choosing a loop
LoopUse when
for-each: for (T x : items)Visiting every element of an array or Iterable; the default choice
for (int i = 0; i < n; i++)You need the index, or to step differently, or to iterate two arrays together
while (condition)The number of iterations is not known in advance
do { } while (condition)The body must run at least once
A streamFiltering, transforming and collecting; see streams

Loop traps that compile without warnings

Each loop in this program compiles cleanly and is wrong in a way that is easy to miss in review. Where a loop would run forever, the program adds a safety limit so it can show what happened.

Java
import java.util.List;

public class LoopTraps {

    public static void main(String[] args) {
        // 1. A floating-point counter may never equal its end value
        int iterations = 0;
        for (double x = 0.0; x != 1.0 && iterations < 20; x += 0.1) {
            iterations++;
        }
        System.out.println("x != 1.0 loop stopped by the safety limit after " + iterations);
        int counted = 0;
        for (int tenths = 0; tenths < 10; tenths++) {
            counted++;                             // count in integers, compute x = tenths / 10.0
        }
        System.out.println("integer counter ran " + counted + " times");

        // 2. An int counter cannot exceed Integer.MAX_VALUE, so "<=" MAX never becomes false
        long laps = 0;
        for (int i = Integer.MAX_VALUE - 2; i <= Integer.MAX_VALUE; i++) {
            if (++laps > 5) {
                System.out.println("i wrapped around to " + i + "; stopped after " + laps);
                break;
            }
        }

        // 3. Off by one: < length visits every index, <= length goes one too far
        int[] data = {10, 20, 30};
        try {
            for (int i = 0; i <= data.length; i++) {
                System.out.print(data[i] + " ");
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("<- then " + e.getMessage());
        }

        // 4. Labeled continue: skip to the next row as soon as a row is invalid
        List<int[]> rows = List.of(new int[] {1, 2}, new int[] {3, -1, 5}, new int[] {6});
        int sum = 0;
        rows:
        for (int[] row : rows) {
            for (int v : row) {
                if (v < 0) {
                    continue rows;                  // ignore the whole row
                }
            }
            for (int v : row) {
                sum += v;
            }
        }
        System.out.println("sum of rows without negatives: " + sum);

        // 5. for-each over a null collection throws NullPointerException
        List<String> missing = null;
        try {
            for (String s : missing) {
                System.out.println(s);
            }
        } catch (NullPointerException e) {
            System.out.println("for-each over null: NullPointerException");
        }
    }
}

Output:

Output
x != 1.0 loop stopped by the safety limit after 20
integer counter ran 10 times
i wrapped around to -2147483646; stopped after 6
10 20 30 <- then Index 3 out of bounds for length 3
sum of rows without negatives: 9
for-each over null: NullPointerException
  1. Adding 0.1 ten times does not give exactly 1.0 (see data types), so x != 1.0 stayed true and only the safety limit stopped the loop. Count with an integer and compute the fraction from it.
  2. Every int is <= Integer.MAX_VALUE, so that condition can never become false: after MAX_VALUE, i++ wrapped around to a negative number and the loop would have continued forever. Use a long counter or a < bound below the maximum.
  3. Indexes run from 0 to length - 1. With <=, the loop printed all three values and then failed on index 3. Prefer for-each when the index is not needed; it cannot get the bounds wrong.
  4. continue rows abandoned a row as soon as it contained a negative number and moved to the next one, so only {1, 2} and {6} were added: 9.
  5. A for-each loop over null throws NullPointerException, because it calls iterator(). Methods that return collections should return an empty one, never null.

Removing elements from a collection while looping over it with for-each is another classic trap; see removing elements while iterating.

Summary

Which construct to use
SituationUse
Two or three conditionsif / else if with braces on every branch
Choosing between two valuesThe ternary operator
One value compared with many constantsA switch expression with arrows
Different handling per typeA pattern matching switch, ideally over a sealed type
Every element of a collectionfor-each, or a stream for transformations
Repeat until a condition changeswhile, or do-while if the body must run once
Leaving nested loopsExtract a method and return, or use a labeled break