Foundation

04 — Control Flow

Previous: 03 Operators & Casting · Next: 05 Loops

▶️ java pkg1core/core5ControlStatements.java


if / else if / else

java
1int score = 82;2if (score >= 90) {3    System.out.println("A");4} else if (score >= 80) {5    System.out.println("B");6} else {7    System.out.println("Below B");8}

Only one branch runs — the first condition that is true.


switch — classic (statement)

java
1int day = 3;2switch (day) {3    case 1: System.out.println("Monday"); break;4    case 2: System.out.println("Tuesday"); break;5    case 3: System.out.println("Wednesday"); break;6    default: System.out.println("Other");7}

⚠️ Without break, execution falls through to the next case.


switch — modern expression (Java 14+)

java
1String type = switch (day) {2    case 1, 2, 3, 4, 5 -> "Weekday";3    case 6, 7          -> "Weekend";4    default -> {5        yield "Invalid";   // yield returns from a block6    }7};

💡 Arrow form -> does not fall through. Switch can return a value.


Pattern matching for switch (Java 21)

java
1sealed interface Shape permits Circle, Rectangle {}2record Circle(double r) implements Shape {}3record Rectangle(double w, double h) implements Shape {}4 5double area = switch (shape) {6    case Circle c    -> Math.PI * c.r() * c.r();7    case Rectangle r -> r.w() * r.h();8};

Works beautifully with sealed types — compiler checks exhaustiveness.


When to use what

Construct Use when
if/else Ranges, complex boolean logic
switch Single variable, many discrete values
switch expression Assigning a result from discrete cases

Practice

  1. Run core5ControlStatements.
  2. Convert a 5-branch if/else grade system to a switch expression.
  3. Add a default case — when is it required?

Next → 05 Loops Related → 01 Core Java