Free Handbook · Every example compiled & verified

Flow Control

if/else, the ternary operator, classic switch and Java 21 switch expressions, while, do-while and for loops, break, continue and labels.

0 / 142 lessons🔥 0 day streak
ShareXLinkedIn

Module 02 · what you'll be able to do

  • Branch with if / else if / else and the ternary operator, and avoid the = versus == trap
  • Write a classic switch statement and explain fall-through
  • Replace it with an arrow-style switch expression that returns a value and is checked for exhaustiveness
  • Choose between while, do-while, for and the enhanced for loop
  • Control loops with break, continue and labelled break
01

if, else if, else and the ternary operator

An if runs its block only when the condition in brackets is true. Unlike C or JavaScript, the condition must be a real boolean — Java will not treat 0, null or an empty string as false. Chain further checks with else if; the first true branch wins and the rest are skipped.

javaMain.java
public class Main {
    static String grade(int score) {
        if (score >= 90) {
            return "A";
        } else if (score >= 75) {
            return "B";
        } else if (score >= 50) {
            return "C";
        } else {
            return "F";
        }
    }

    public static void main(String[] args) {
        System.out.println(grade(95));
        System.out.println(grade(75));
        System.out.println(grade(49));

        int stock = 0;
        String label = stock > 0 ? "In stock" : "Sold out";   // ternary
        System.out.println(label);
    }
}
Outputcompiled & run with real Java
A
B
F
Sold out
Your turn

Swap the order of the first two checks (>= 75 first). Now 95 prints B — order matters because the first match wins.

Always use braces
Java allows if (x) doThing(); without braces, but only the next single statement belongs to the if. Add a second indented line later and it runs unconditionally. Most team style guides require braces on every if, else, for and while.
Error you will hit

int cannot be converted to boolean — = instead of ==

java
public class Main {
    public static void main(String[] args) {
        int score = 70;
        if (score = 100) {
            System.out.println("Perfect");
        }
    }
}
Main.java:4: error: incompatible types: int cannot be converted to boolean
        if (score = 100) {
                  ^
1 error
Why the compiler said that

= assigns; == compares. score = 100 is an assignment expression whose value is the int 100, and an if condition must be a boolean. In C this bug compiles and silently runs; Java's type checker catches it.

The fix

Use == to compare.

java
if (score == 100) {
02

The classic switch statement

A switch compares one value against several case labels. It works on int, char, String, enums and (since Java 21) any object via patterns. The classic colon form has one famous trap: fall-through. Without a break, execution runs straight into the next case's code.

javaMain.java
public class Main {
    public static void main(String[] args) {
        String command = "stop";
        switch (command) {
            case "start":
                System.out.println("Starting");
                break;
            case "stop":
                System.out.println("Stopping");
                break;
            default:
                System.out.println("Unknown command");
        }

        int level = 2;
        System.out.println("Access for level " + level + ":");
        switch (level) {            // deliberate fall-through
            case 3:
                System.out.println("  delete");
            case 2:
                System.out.println("  write");
            case 1:
                System.out.println("  read");
        }
    }
}
Outputcompiled & run with real Java
Stopping
Access for level 2:
  write
  read
Your turn

Remove the break after "Stopping" and predict the output. (It also prints "Unknown command".)

Fall-through is a feature that is usually a bug
Grouping cases on purpose (the access-level example) is fine, but most fall-through in real code is a forgotten break. The arrow form in the next lesson never falls through, which is why modern Java code prefers it.
03

Switch expressions (Java 14+)

The arrow form case X -> ... runs exactly one branch — no break, no fall-through — and a switch used as an expression produces a value you can assign or return. Several labels can share a branch (case 6, 7 ->). A branch that needs several statements uses a block and yield to hand back its value.

javaMain.java
public class Main {
    enum Size { SMALL, MEDIUM, LARGE }

    public static void main(String[] args) {
        int day = 6;
        String type = switch (day) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Invalid day";
        };
        System.out.println(type);

        Size size = Size.MEDIUM;
        int price = switch (size) {        // all enum values covered: no default needed
            case SMALL -> 100;
            case MEDIUM -> 150;
            case LARGE -> {
                int base = 150;
                yield base + 50;           // yield returns from a block branch
            }
        };
        System.out.println(size + " costs " + price);
    }
}
Outputcompiled & run with real Java
Weekend
MEDIUM costs 150
Your turn

Add EXTRA_LARGE to the enum and run it. The compiler now rejects the second switch until you handle the new value — that is exhaustiveness checking protecting you.

Error you will hit

the switch expression does not cover all possible input values

java
public class Main {
    public static void main(String[] args) {
        int day = 3;
        String name = switch (day) {
            case 1 -> "Mon";
            case 2 -> "Tue";
            case 3 -> "Wed";
        };
        System.out.println(name);
    }
}
Main.java:4: error: the switch expression does not cover all possible input values
        String name = switch (day) {
                      ^
1 error
Why the compiler said that

A switch expression must always produce a value. An int can be any of four billion values, and there is no branch for 4, 5 or -1, so the compiler cannot guarantee name gets assigned.

The fix

Add a default branch (or cover every constant, which is possible for enums and sealed types).

java
String name = switch (day) {
    case 1 -> "Mon";
    case 2 -> "Tue";
    case 3 -> "Wed";
    default -> "Other";
};

Classic switch statement

  • case X: with a colon
  • Falls through without break
  • Does not produce a value
  • Missing cases compile silently

Arrow switch expression

  • case X -> with an arrow
  • Never falls through
  • Returns a value; blocks use yield
  • Must be exhaustive — the compiler checks
04

while and do-while loops

A while loop checks its condition before each pass, so it may run zero times. A do-while loop checks after each pass, so its body always runs at least once — the natural shape for "ask, then check the answer". Use a while when you do not know the number of iterations in advance.

javaMain.java
public class Main {
    public static void main(String[] args) {
        int n = 4096;
        int digits = 0;
        int sum = 0;
        while (n > 0) {
            sum += n % 10;     // last digit
            n /= 10;           // drop the last digit
            digits++;
        }
        System.out.println(digits + " digits, digit sum " + sum);

        int attempts = 0;
        do {
            attempts++;
            System.out.println("attempt " + attempts);
        } while (attempts < 3);

        int x = 100;
        do {
            System.out.println("do-while ran once even though x >= 10");
        } while (x < 10);
    }
}
Outputcompiled & run with real Java
4 digits, digit sum 19
attempt 1
attempt 2
attempt 3
do-while ran once even though x >= 10
Your turn

Change n to 0. The while loop body never runs, so it reports 0 digits — how would you fix that edge case?

Infinite loops
If nothing inside the loop ever makes the condition false, it runs forever. Stop a runaway program with Ctrl + C in the terminal, or the red stop button in your IDE. while (true) is fine when the body has a break or return.
05

for loops and the enhanced for

The classic for (init; condition; update) puts the three parts of a counting loop on one line. The enhanced for (for (int x : array)) walks every element of an array or collection without an index — use it whenever you do not need the index.

javaMain.java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        for (int i = 10; i > 0; i -= 3) {
            System.out.print(i + " ");
        }
        System.out.println();

        int[] prices = {120, 80, 45};
        int total = 0;
        for (int p : prices) {          // enhanced for: "for each p in prices"
            total += p;
        }
        System.out.println("total = " + total);

        for (int row = 1; row <= 3; row++) {        // nested loops
            for (int col = 1; col <= row; col++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Outputcompiled & run with real Java
1 2 3 4 5
10 7 4 1
total = 245
*
**
***
Your turn

Print the 7 times table from 7 x 1 to 7 x 10 with a classic for loop.

VisualizeSumming with a for loopStep 1 / 9
int sum = 0;
for (int i = 1; i <= 3; i++) {
sum += i;
}
System.out.println(sum);
Line 1

sum starts at 0.

Variables now
sum0
All 9 steps as a table
StepLineWhat happenedVariables now
11sum starts at 0.sum = 0
22Init runs once: i = 1. Condition 1 <= 3 is true, so the body runs.sum = 0 i = 1
33sum becomes 0 + 1.sum = 1 i = 1
42Update i++, then check 2 <= 3: true.sum = 1 i = 2
53sum becomes 1 + 2.sum = 3 i = 2
62i becomes 3; 3 <= 3 is still true.sum = 3 i = 3
73sum becomes 3 + 3.sum = 6 i = 3
82i becomes 4; 4 <= 3 is false, so the loop ends. i goes out of scope here.sum = 6
95Print the result.
Error you will hit

cannot find symbol — the loop variable is out of scope

java
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(i);
        }
        System.out.println(i);
    }
}
Main.java:6: error: cannot find symbol
        System.out.println(i);
                           ^
  symbol:   variable i
  location: class Main
1 error
Why the compiler said that

A variable declared in the for header exists only inside the loop. After the closing brace it is gone, so the name i means nothing on line 6. "cannot find symbol" is Java's general message for a name it cannot resolve — also caused by typos and missing imports.

The fix

Declare the variable before the loop if you need its final value afterwards.

java
int i;
for (i = 0; i < 3; i++) {
    System.out.println(i);
}
System.out.println("stopped at " + i);
06

break, continue and labels

break leaves the loop immediately. continue skips the rest of the current pass and jumps to the next one. Both act on the innermost loop; to break out of an outer loop from inside a nested one, put a label on the outer loop and write break outer;.

javaMain.java
public class Main {
    public static void main(String[] args) {
        int[] orders = {40, -1, 75, 0, 120, 999, 60};

        for (int amount : orders) {
            if (amount <= 0) {
                continue;               // skip invalid rows
            }
            if (amount == 999) {
                System.out.println("end marker, stop");
                break;                  // leave the loop
            }
            System.out.println("process " + amount);
        }

        int[][] grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        outer:
        for (int[] row : grid) {
            for (int value : row) {
                if (value == 5) {
                    System.out.println("found 5, leaving both loops");
                    break outer;
                }
            }
        }
    }
}
Outputcompiled & run with real Java
process 40
process 75
process 120
end marker, stop
found 5, leaving both loops
Your turn

Change break outer; to plain break; and add a print after the inner loop. Now the outer loop continues to the third row.

Error you will hit

unreachable statement

java
public class Main {
    public static void main(String[] args) {
        while (true) {
            System.out.println("tick");
        }
        System.out.println("done");
    }
}
Main.java:6: error: unreachable statement
        System.out.println("done");
        ^
1 error
Why the compiler said that

while (true) with no break can never finish, so the compiler proves line 6 can never run and treats dead code as an error rather than a warning.

The fix

Give the loop a way out with break (or a real condition).

java
int ticks = 0;
while (true) {
    System.out.println("tick");
    if (++ticks == 3) break;
}
System.out.println("done");
Condition
A boolean expression that decides whether a branch or loop body runs. Java never converts numbers or null to boolean.
Ternary operator
cond ? a : b — an expression that picks one of two values.
Fall-through
In a colon-style switch, running into the next case because there was no break.
Switch expression
An arrow-style switch that produces a value and must cover every possible input.
yield
Returns a value from a block branch of a switch expression.
Enhanced for
for (T x : collection) — iterates every element without an index.
Label
A name before a loop (outer:) so break outer or continue outer can target it.
Quick check

How many times does for (int i = 0; i < 10; i += 3) { } run its body?

JuniorWhat is the difference between a switch statement and a switch expression in modern Java?

A switch statement performs actions; with the colon form it falls through without break and missing cases compile silently. A switch expression (Java 14+) evaluates to a value, uses case X -> arrows that never fall through, uses yield to return from a block branch, and must be exhaustive — the compiler errors if an input value is not covered. For enums and sealed types, covering every constant is enough, so adding a new enum value breaks the build at every switch that needs updating.

What they are really testing: Whether you know the Java 14+ features and why exhaustiveness checking is a safety net, not just syntax sugar.

Frequently asked questions

Can I use a String in a Java switch?
Yes, since Java 7. The comparison uses equals(), so it compares content, and it is case-sensitive. Passing a null String to a switch throws a NullPointerException unless you add case null (Java 21).
When should I use a while loop instead of a for loop?
Use for when you are counting or walking a known range or collection. Use while when you loop until something happens — input arrives, a queue empties, a value converges — and the number of passes is not known in advance.
Is it bad practice to use break inside a loop?
No. break to stop searching once you have found what you need is clear and efficient. What hurts readability is several breaks and continues scattered through a long loop body; at that point, extract the loop into a method and use return.

Finish the Java handbook, then get hired

Sit the exam for your certificate, run your resume through the ATS checker, and see the jobs that ask for exactly this.

Check my resume
Found this course useful? Share it.
ShareXLinkedIn

Comments

0

Join the conversation. Sign in to leave a comment — we'd love to hear your thoughts.