Script Valley
Java: Complete Language Course
Java FundamentalsLesson 1.4

Java if-else and switch control flow

if statement, else-if chain, nested conditionals, switch statement, switch expression, fall-through, break, default case

Conditional Control Flow

Control flow determines which code block executes based on runtime conditions. Use if-else for range checks and complex boolean logic; use switch when matching a single variable against discrete values.

if-else Chain

int score = 72;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else if (score >= 70) {
    System.out.println("C");
} else {
    System.out.println("F");
}
// Output: C

Each condition is tested top-down. Once a branch matches, the rest are skipped. Always put the most specific or most common case first for both correctness and performance.

switch Statement

String day = "MON";
switch (day) {
    case "MON":
    case "TUE":
        System.out.println("Weekday");
        break;
    case "SAT":
    case "SUN":
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Unknown");
}

Without break, execution falls through to the next case. This is occasionally intentional (grouping MON and TUE above), but usually a bug.

switch Expression (Java 14+)

String label = switch (score / 10) {
    case 10, 9 -> "A";
    case 8    -> "B";
    case 7    -> "C";
    default   -> "F";
};

Arrow syntax eliminates fall-through entirely and lets switch return a value directly. Prefer it over the classic switch statement in modern Java โ€” it is safer, more concise, and expresses intent clearly.

Up next

Java for loop, while loop, and loop control

Sign in to track progress

Java if-else and switch control flow โ€” Java Fundamentals โ€” Java: Complete Language Course โ€” Script Valley โ€” Script Valley