Day 3: Control Flow
What You'll Learn Today
- Conditional branching (if / else)
- switch statements and switch expressions
- for loops
- while / do-while loops
- break and continue
if Statements
int score = 85;
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("D");
}
// Output: B
flowchart TB
Start["score = 85"]
C1{"score >= 90?"}
C2{"score >= 80?"}
C3{"score >= 70?"}
A["A"]
B["B"]
C["C"]
D["D"]
Start --> C1
C1 -->|"Yes"| A
C1 -->|"No"| C2
C2 -->|"Yes"| B
C2 -->|"No"| C3
C3 -->|"Yes"| C
C3 -->|"No"| D
style B fill:#22c55e,color:#fff
Ternary Operator
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status); // Adult
switch Statements
Traditional switch Statement
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other");
break;
}
Caution: Forgetting
breakcauses fall-through, where the next case executes as well.
switch Expressions (Java 14+)
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Unknown";
};
System.out.println(dayName); // Wednesday
Recommendation: From Java 14 onward, prefer the arrow-style switch expression. It eliminates the risk of missing
breakand can return a value.
Matching Multiple Values
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Unknown";
};
Types Supported by switch
| Type | Example |
|---|---|
int, byte, short, char |
case 1: |
String |
case "hello": |
enum |
case MONDAY: |
for Loops
Basic for Loop
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
// i = 0, 1, 2, 3, 4
flowchart TB
Init["int i = 0<br>Initialization"]
Cond{"i < 5?"}
Body["Loop Body<br>Execute"]
Update["i++<br>Update"]
End["Loop Ends"]
Init --> Cond
Cond -->|"true"| Body --> Update --> Cond
Cond -->|"false"| End
style Init fill:#3b82f6,color:#fff
style Cond fill:#f59e0b,color:#fff
style Body fill:#22c55e,color:#fff
style Update fill:#8b5cf6,color:#fff
Counting Down
for (int i = 5; i > 0; i--) {
System.out.println(i);
}
// 5, 4, 3, 2, 1
Nested for Loops
// Multiplication table
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
System.out.printf("%3d", i * j);
}
System.out.println();
}
Enhanced for Loop (for-each)
Iterates through every element in an array or collection:
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Recommendation: Use the enhanced for loop when you need to process every element and don't need the index.
while Loops
while
int count = 0;
while (count < 5) {
System.out.println("count = " + count);
count++;
}
do-while
int count = 0;
do {
System.out.println("count = " + count);
count++;
} while (count < 5);
| Loop | Condition Check | Minimum Executions |
|---|---|---|
while |
Before the body | 0 |
do-while |
After the body | 1 |
break and continue
break
Exits the loop immediately:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit when i reaches 5
}
System.out.println(i);
}
// 0, 1, 2, 3, 4
continue
Skips the rest of the current iteration:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
// 1, 3, 5, 7, 9
Labeled break
Breaks out of nested loops all at once:
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break outer; // Exit both loops
}
System.out.printf("(%d, %d) ", i, j);
}
}
// (0, 0) (0, 1) (0, 2) (1, 0)
Practice: Number Guessing Game
import java.util.Random;
import java.util.Scanner;
public class NumberGuessing {
public static void main(String[] args) {
Random random = new Random();
int answer = random.nextInt(100) + 1; // 1 to 100
Scanner scanner = new Scanner(System.in);
int attempts = 0;
System.out.println("=== Number Guessing Game ===");
System.out.println("Guess a number between 1 and 100.");
while (true) {
System.out.print("Your guess: ");
int guess = scanner.nextInt();
attempts++;
if (guess == answer) {
System.out.printf("Correct! You got it in %d attempts!%n", attempts);
break;
} else if (guess < answer) {
System.out.println("Too low.");
} else {
System.out.println("Too high.");
}
}
scanner.close();
}
}
Summary
| Concept | Description |
|---|---|
if / else |
Conditional branching |
switch |
Branch by value (arrow syntax recommended) |
for |
Loop with a known number of iterations |
for-each |
Iterate through every element in a collection |
while |
Loop while a condition is true |
do-while |
Loop that executes at least once |
break |
Exit a loop |
continue |
Skip the current iteration |
Key Takeaways
- Use switch expressions (
->syntax) to avoid missingbreak - Use the enhanced for loop to process all elements
while(true)+breakis useful for loops with complex exit conditions- Labeled break lets you exit nested loops in one step
Exercises
Exercise 1: Basic
Write a FizzBuzz program: print numbers from 1 to 100, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
Exercise 2: Applied
Using Scanner, repeatedly read numbers from the user. When 0 is entered, display the total and average of all previously entered numbers, then exit.
Exercise 3: Challenge
Using nested for loops, write a program that prints the following triangle pattern:
*
**
***
****
*****
References
Next up: On Day 4, we'll cover Arrays and Strings. You'll learn how to work with collections of data and master string manipulation.