← Back to Java series
β˜•
Basics
Basics Β· Prerequisite: previous lecture

04. Control Flow

**Control flow** statements direct how code branches or repeats. Java's control flow looks like C's, but with modern additions like JDK 14+'s **switch expression**.

JavaJDKbasicscontrol flow
Duration
⏱ ~1-1.5 hours
Level
πŸ“Š Beginner
Prerequisite
🎯 Previous lecture or equivalent knowledge
OUTCOME
**Control flow** statements direct how code branches or repeats. Java's control flow looks like C's, but with modern additions like JDK 14+'s **switch expression**.

What you'll learn

  • 1Write `if` / `else if` / `else` chains
  • 2Use the new **switch expression** (`->` / `yield`)
  • 3Know the differences between `for`, `while`, `do-while`, and the **enhanced for**
  • 4Use `break`, `continue`, and labeled jumps

Overview

**Control flow** statements direct how code branches or repeats. Java's control flow looks like C's, but with modern additions like JDK 14+'s **switch expression**.

Core Concepts

1) `if` / `else if` / `else`

java
int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C or below");
}

2) Switch expression (JDK 14+)

java
int day = 3;
String name = switch (day) {
    case 1, 2, 3, 4, 5 -> "weekday";
    case 6, 7 -> "weekend";
    default -> "error";
};
System.out.println(name);
  • Group several values on one arm: `case 1, 2, 3 ->`
  • Use a block + `yield` for multi-line arms:
java
  String s = switch (n) {
      case 1 -> "one";
      case 2 -> {
          System.out.println("two!");
          yield "two";
      }
      default -> "?";
  };

3) The four loop forms

java
for (int i = 0; i < 3; i++) { ... }

int j = 0;
while (j < 3) { j++; }

int k = 0;
do { k++; } while (k < 3);

int[] nums = {1, 2, 3};
for (int n : nums) { System.out.println(n); }   // enhanced for

4) `break` / `continue`

java
for (int i = 0; i < 10; i++) {
    if (i == 3) continue;   // skip this iteration
    if (i == 6) break;      // exit the loop
    System.out.print(i + " ");   // 0 1 2 4 5
}

Examples

Example 1 β€” `IfElseDemo.java`: basic branching

java
public class IfElseDemo {
    public static void main(String[] args) {
        int score = 72;
        String grade;
        if (score >= 90) grade = "A";
        else if (score >= 80) grade = "B";
        else if (score >= 70) grade = "C";
        else if (score >= 60) grade = "D";
        else grade = "F";
        System.out.println("score " + score + " -> " + grade);
    }
}

**Output**

text
score 72 -> C

**Note:** single-line `if` bodies can omit braces, but **the official convention is to use braces**.

Example 2 β€” `SwitchExpression.java`: `->` / `yield`

java
public class SwitchExpression {
    public static void main(String[] args) {
        int day = 3;
        String kind = switch (day) {
            case 1, 2, 3, 4, 5 -> "weekday";
            case 6, 7 -> "weekend";
            default -> "error";
        };
        System.out.println("day " + day + ": " + kind);

        int n = 2;
        String word = switch (n) {
            case 1 -> "one";
            case 2 -> {
                System.out.println("two!");
                yield "two";
            }
            default -> "?";
        };
        System.out.println(word);
    }
}

**Output**

text
day 3: weekday
two!
two

**Note:** a switch expression **must produce a value** (so it needs a `default`).

Example 3 β€” `Loops.java`: for / while / enhanced for

java
public class Loops {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) sum += i;
        System.out.println("1+...+5 = " + sum);

        int j = 0;
        while (j < 3) {
            System.out.print(j + " ");
            j++;
        }
        System.out.println();

        int[] nums = {10, 20, 30};
        for (int n : nums) System.out.print(n + " ");
        System.out.println();
    }
}

**Output**

text
1+...+5 = 15
0 1 2
10 20 30 

**Note:** the **enhanced for** is safest when you don't need an index.

Example 4 β€” `BreakContinue.java`: break / continue

java
public class BreakContinue {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 3) continue;
            if (i == 6) break;
            System.out.print(i + " ");
        }
        System.out.println();

        outer:
        for (int i = 0; i < 3; i++) {
            for (int k = 0; k < 3; k++) {
                if (i + k == 3) break outer;
                System.out.print("(" + i + "," + k + ") ");
            }
        }
        System.out.println();
    }
}

**Output**

text
0 1 2 4 5
(0,0) (0,1) (0,2) (1,0) (1,1) 

**Note:** **labeled break** is useful for escaping deeply-nested loops, but overusing it hurts readability.

Full example code (src/)

src/BreakContinue.java

java
public class BreakContinue {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 3) continue;
            if (i == 6) break;
            System.out.print(i + " ");
        }
        System.out.println();

        outer:
        for (int i = 0; i < 3; i++) {
            for (int k = 0; k < 3; k++) {
                if (i + k == 3) break outer;
                System.out.print("(" + i + "," + k + ") ");
            }
        }
        System.out.println();
    }
}

src/IfElseDemo.java

java
public class IfElseDemo {
    public static void main(String[] args) {
        int score = 72;
        String grade;
        if (score >= 90) grade = "A";
        else if (score >= 80) grade = "B";
        else if (score >= 70) grade = "C";
        else if (score >= 60) grade = "D";
        else grade = "F";
        System.out.println("score " + score + " -> " + grade);
    }
}

src/Loops.java

java
public class Loops {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) sum += i;
        System.out.println("1+...+5 = " + sum);

        int j = 0;
        while (j < 3) {
            System.out.print(j + " ");
            j++;
        }
        System.out.println();

        int[] nums = {10, 20, 30};
        for (int n : nums) System.out.print(n + " ");
        System.out.println();
    }
}

src/SwitchExpression.java

java
public class SwitchExpression {
    public static void main(String[] args) {
        int day = 3;
        String kind = switch (day) {
            case 1, 2, 3, 4, 5 -> "weekday";
            case 6, 7 -> "weekend";
            default -> "error";
        };
        System.out.println("day " + day + ": " + kind);

        int n = 2;
        String word = switch (n) {
            case 1 -> "one";
            case 2 -> {
                System.out.println("two!");
                yield "two";
            }
            default -> "?";
        };
        System.out.println(word);
    }
}

Common Mistakes

  1. Writing `if (a = 1)` with `=` instead of `==` β†’ compile error (int where boolean is required)
  2. Off-by-one bugs from `<` vs `<=`
  3. Forgetting `break` in a classic `switch` and falling through
  4. Modifying a collection inside enhanced for β†’ `ConcurrentModificationException`
  5. Missing `default` in a switch expression

Summary

  • Branch with `if` or a switch expression
  • Iterate with `for` / `while` / enhanced for
  • `break` / `continue` and labeled jumps are occasionally useful

Practice

# Practice - 04. Control Flow

## Exercise 1 β€” FizzBuzz

  • File: `Homework01.java`
  • Key concepts: `for`, `if/else if`

Requirements

  • Print numbers 1..15.
  • Multiples of 3 print `Fizz`, multiples of 5 print `Buzz`, multiples of 15 print `FizzBuzz`, everything else prints the number.

Expected output

text
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Hint

  • Check the multiple-of-15 case **first**.

## Exercise 2 β€” Menu selection

  • File: `Homework02.java`
  • Key concepts: switch expression

Requirements

  • Given `menu = 2`, use a switch expression to return:
  • 1 β†’ "New", 2 β†’ "Recommended", 3 or 4 β†’ "Bestseller", else β†’ "None"
  • Print `Selected: Recommended`.

Expected output

text
Selected: Recommended

## Exercise 3 β€” Multiplication table 2 ~ 5

  • File: `Homework03.java`
  • Key concepts: nested `for`

Requirements

  • Print the multiplication tables for 2..5.
  • Format like `2 * 1 = 2`.
  • Separate tables with a blank line.

Expected output

text
2 * 1 = 2
2 * 2 = 4
...(truncated)

Hint

  • Outer loop is the multiplicand, inner loop is the multiplier.

## Solutions After trying it yourself, compare with [`answer/`](./answer/).

Solution code (homework/answer/)

answer/Homework01.java

java
/** FizzBuzz 1..15. */
public class Homework01 {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            if (i % 15 == 0) System.out.println("FizzBuzz");
            else if (i % 3 == 0) System.out.println("Fizz");
            else if (i % 5 == 0) System.out.println("Buzz");
            else System.out.println(i);
        }
    }
}

answer/Homework02.java

java
/** Menu via switch expression. */
public class Homework02 {
    public static void main(String[] args) {
        int menu = 2;
        String label = switch (menu) {
            case 1 -> "New";
            case 2 -> "Recommended";
            case 3, 4 -> "Bestseller";
            default -> "None";
        };
        System.out.println("Selected: " + label);
    }
}

answer/Homework03.java

java
/** Multiplication tables 2..5. */
public class Homework03 {
    public static void main(String[] args) {
        for (int dan = 2; dan <= 5; dan++) {
            for (int i = 1; i <= 9; i++) {
                System.out.println(dan + " * " + i + " = " + (dan * i));
            }
            System.out.println();
        }
    }
}

Try It Yourself

bash
cd 01_basics/04_control_flow/src
javac SwitchExpression.java
java SwitchExpression

Next Lecture

[05_Methods](../05_λ©”μ„œλ“œ/) β€” method declaration, overloading, `static`, varargs.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—