Skip to content

Chapter 4 of 37

Control Flow

Make decisions with if, else, classic switch, and modern switch expressions.

28 minutes 10 quick checksBy Subha Prasad
Lesson 4 of 37Course navigation

Lesson content

Read, practise, then check your understanding

An if condition must be boolean. Order an else-if chain from specific cases to general ones, use braces consistently, and prefer guard clauses to deep nesting.

Modern selection

static String result(int score) {
    if (score < 0 || score > 100) return "invalid";
    return switch (score / 10) {
        case 10, 9, 8 -> "excellent";
        case 7, 6, 5 -> "pass";
        default -> "retry";
    };
}

Classic colon-style switch may fall through and usually needs break. Arrow cases do not fall through and a switch expression must produce a value; a block case uses yield. Switch supports integral-compatible values, enums, strings, and increasingly expressive pattern matching in modern Java versions. Handle null deliberately where the selected language level supports it. When branching grows around types or responsibilities, polymorphism or data-driven lookup may express the model better.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes if statement?
Which Java term matches this description: A branch that runs when its boolean condition is true.
Which statement best describes else-if chain?
Which Java term matches this description: Ordered conditions where only the first matching branch runs.
Which statement best describes switch expression?
Which Java term matches this description: A selection construct that can yield a value with arrow cases.
Which statement best describes yield?
Which Java term matches this description: A statement producing a value from a switch expression block.
Which statement best describes guard clause?
Which Java term matches this description: An early return that handles invalid or exceptional input.

0 of 10 checks passed

Your progress is saved on this device.