V
Vel·ToolKit
Simple · Fast · Ready to use
EN
Chapter 4 of 20

Control Flow

if / for / while / break / switch statement + expression

if Statements

The condition must be of type boolean (unlike C, where an int can serve as a condition). else-if chains are common.

// IfDemo.java
public class IfDemo {
    public static void main(String[] args) {
        int score = 75;
        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 80) {
            System.out.println("B");
        } else if (score >= 60) {
            System.out.println("C");
        } else {
            System.out.println("F");
        }
    }
}

for Loops

C-style three parts: init; condition; step. Exits when the condition is false.

// ForDemo.java
public class ForDemo {
    public static void main(String[] args) {
        // three parts
        for (int i = 0; i < 3; i++) {
            System.out.println("i=" + i);
        }

        // multiple variables
        for (int i = 0, j = 10; i < j; i++, j--) {
            System.out.println(i + " " + j);
        }
    }
}

Enhanced for (for-each)

For iterating an array or any collection implementing Iterable. Concise but you can't get the index — use the three-part form if you need it.

// ForEach.java
import java.util.List;

public class ForEach {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        for (int n : nums) {
            System.out.println(n);
        }

        List<String> names = List.of("Alice", "Bob", "Carol");
        for (String name : names) {
            System.out.println(name);
        }
    }
}

while and do-while

while checks first then runs (may not run at all); do-while runs at least once then checks.

// WhileDemo.java
public class WhileDemo {
    public static void main(String[] args) {
        int n = 5;
        while (n > 0) {
            System.out.println(n);
            n--;
        }

        int input;
        int tries = 0;
        do {
            input = (int) (Math.random() * 10);
            tries++;
        } while (input != 7);
        System.out.println("got 7 after " + tries + " tries");
    }
}

break / continue / Labels

break exits the nearest loop / switch; continue moves to the next iteration. Java supports labels — the cleanest way to break out of nested loops.

// Labels.java
public class Labels {
    public static void main(String[] args) {
        outer:
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i * j > 6) {
                    System.out.println("stop at " + i + "," + j);
                    break outer;     // break the outer loop
                }
                if (j == 2) {
                    continue outer;  // continue with the outer loop's next iteration
                }
                System.out.println(i + "," + j);
            }
        }
    }
}

Traditional switch Statement

A traditional switch matches by case label; without break it "falls through" to the next case (a historical wart that often causes bugs). switch supports int / String / enum, etc.

// SwitchOld.java
public class SwitchOld {
    public static void main(String[] args) {
        String day = "MON";
        switch (day) {
            case "SAT":
            case "SUN":
                System.out.println("weekend");
                break;
            case "MON":
            case "TUE":
            case "WED":
            case "THU":
            case "FRI":
                System.out.println("workday");
                break;
            default:
                System.out.println("unknown");
        }
    }
}

switch Expression (Java 14+)

Modern switch: arrow syntax, no fall-through, usable as an expression for assignment, multiple cases combined with commas.

// SwitchNew.java
public class SwitchNew {
    public static void main(String[] args) {
        String day = "MON";

        // as a statement
        switch (day) {
            case "SAT", "SUN" -> System.out.println("weekend");
            case "MON", "TUE", "WED", "THU", "FRI" -> System.out.println("workday");
            default -> System.out.println("unknown");
        }

        // as an expression: return a value directly
        int code = switch (day) {
            case "SAT", "SUN" -> 0;
            case "MON", "TUE", "WED", "THU", "FRI" -> 1;
            default -> -1;
        };
        System.out.println("code=" + code);
    }
}

switch Expression + yield (Complex Branches)

If a case needs multiple lines to compute its value, use { ... yield value; }. yield is the "return" keyword specific to switch expressions.

// SwitchYield.java
public class SwitchYield {
    public static void main(String[] args) {
        int month = 2;
        int year = 2024;

        int days = switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 -> 31;
            case 4, 6, 9, 11 -> 30;
            case 2 -> {
                boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
                yield leap ? 29 : 28;
            }
            default -> throw new IllegalArgumentException("bad month: " + month);
        };

        System.out.println(year + "-" + month + " has " + days + " days");
    }
}