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**.
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`
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+)
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:
String s = switch (n) {
case 1 -> "one";
case 2 -> {
System.out.println("two!");
yield "two";
}
default -> "?";
};3) The four loop forms
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 for4) `break` / `continue`
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
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**
score 72 -> C**Note:** single-line `if` bodies can omit braces, but **the official convention is to use braces**.
Example 2 β `SwitchExpression.java`: `->` / `yield`
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**
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
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**
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
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**
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
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
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
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
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
- Writing `if (a = 1)` with `=` instead of `==` β compile error (int where boolean is required)
- Off-by-one bugs from `<` vs `<=`
- Forgetting `break` in a classic `switch` and falling through
- Modifying a collection inside enhanced for β `ConcurrentModificationException`
- 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
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzHint
- 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
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
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
/** 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
/** 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
/** 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
cd 01_basics/04_control_flow/src
javac SwitchExpression.java
java SwitchExpressionNext Lecture
[05_Methods](../05_λ©μλ/) β method declaration, overloading, `static`, varargs.
All lecture materials and example code are openly available on GitHub.
View on GitHub β