🚦 Lesson 5: Control Flow (Decision Making)
⏱️ Estimated time: 25 minutes | Difficulty: Beginner
Logic Power
Control flow statements allow your Java program to execute different blocks of code based on conditions.
If / Else
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
// Output: Grade: B
Switch Statement
String day = "Monday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.println("Weekday");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend!");
break;
default:
System.out.println("Invalid day");
}
// Java 14+ Switch Expression (modern!)
String type = switch (day) {
case "Saturday", "Sunday" -> "Weekend";
default -> "Weekday";
};
Nested Conditions
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive!");
} else {
System.out.println("Get a license first.");
}
} else {
System.out.println("Too young to drive.");
}
// Cleaner with &&
if (age >= 18 && hasLicense) {
System.out.println("You can drive!");
}
✅ Quick Quiz
❓ What happens without 'break' in switch?
❓ What does 'else if' do?
❓ Can switch work with Strings in Java?