Lesson 4 • Beginner
Control Flow in Java
So far, every line of your code runs from top to bottom, every single time. Control flow changes that — it lets your program make decisions. Think of it like a traffic intersection: without signals, every car goes straight. With a traffic light, cars stop or go depending on the signal. That's what if, else, and switch do for your code.
What You'll Learn
- ✅ How
ifstatements let your code choose what to do - ✅ Adding
elsefor "otherwise do this" paths - ✅ Chaining with
else iffor multiple conditions (like a grade calculator) - ✅ Nested if statements — decisions inside decisions
- ✅
switchstatements — clean alternative when comparing one value against many options - ✅ The ternary operator — a one-line shortcut for simple if/else
- ✅ When to use if vs switch vs ternary (and common mistakes to avoid)
📋 Before You Start
This lesson builds on what you learned in Lessons 1-3. You should already know how to:
- Write and run a Java program with
main() - Declare variables like
int age = 20; - Use comparison operators like
==,>,<,>= - Use logical operators like
&&(AND) and||(OR)
If any of that is fuzzy, go back to Lesson 3: Operators for a quick review.
1️⃣ The Basic If Statement — "Do This Only If..."
The if statement is the simplest decision-maker. It checks a condition (something that's either true or false), and if it's true, it runs the code inside the curly braces. If it's false, it skips that code entirely.
Here's the pattern you'll use thousands of times:
if (condition) {
// This code ONLY runs when condition is true
}
// Code here runs no matter what
// Real example:
int temperature = 35;
if (temperature > 30) {
System.out.println("It's hot outside! ☀️");
}
// Output: It's hot outside! ☀️
int temperature2 = 15;
if (temperature2 > 30) {
System.out.println("It's hot outside!");
}
// Output: (nothing — the condition was false, so it was skipped)🔑 Key point: The condition inside the parentheses () must evaluate to true or false. This is why you learned comparison operators (>, <, ==) in the last lesson — they produce boolean values that if can use.
2️⃣ If-Else — "Do This, Otherwise Do That"
A plain if only handles the "yes" case. But what if you want to do something different when the condition is false? That's where else comes in. It's like saying "if this is true, do A; otherwise, do B."
int age = 20;
if (age >= 18) {
System.out.println("You are an adult. You can vote! 🗳️");
} else {
System.out.println("You are a minor. You can't vote yet.");
}
// Output: You are an adult. You can vote! 🗳️
// Try changing age to 15 — now the else block runs insteadExactly one block always runs. If the condition is true, the if block runs and the else block is skipped. If the condition is false, the if block is skipped and the else block runs. There's no scenario where both run, or neither runs.
3️⃣ Else If — Multiple Conditions in Order
What if you have more than two possibilities? For example, a grade calculator needs to check A, B, C, D, and F — that's five options, not just two. Use else if to chain conditions together:
int score = 85;
String grade;
if (score >= 90) {
grade = "A"; // 90-100
} else if (score >= 80) {
grade = "B"; // 80-89
} else if (score >= 70) {
grade = "C"; // 70-79
} else if (score >= 60) {
grade = "D"; // 60-69
} else {
grade = "F"; // Below 60
}
System.out.println("Score: " + score + " → Grade: " + grade);
// Output: Score: 85 → Grade: B⚠️ Order matters! Java checks conditions from top to bottom and runs the first match. Once a match is found, ALL remaining else-if/else blocks are skipped. If you put score >= 60 first, a score of 95 would get "D" because 95 >= 60 is also true!
Rule of thumb: Put the most specific (or highest) condition first, then work your way down to the most general. The final else acts as a "catch everything else" safety net.
Try It: Grade Calculator
Change the scores and see how if-else-if assigns grades
// 💡 Try modifying this code and see what happens!
// Grade Calculator — Java logic simulated in JavaScript
console.log("=== Grade Calculator ===\n");
// 🎯 Try changing these scores and re-running!
let scores = [95, 85, 72, 63, 45];
for (let score of scores) {
let grade;
if (score >= 90) {
grade = "A ⭐"; // 90-100: Excellent
} else if (score >= 80) {
grade = "B 👍"; // 80-89: Good
} else if (score >= 70) {
grade = "C 👌"; // 70-79: Average
} else if (score
...4️⃣ Nested If — Decisions Inside Decisions
Sometimes you need to check a condition, and then check another condition inside that. This is called nesting. Think of it like a security checkpoint: first, check if you have a ticket. If yes, then check if it's VIP or regular.
boolean hasTicket = true;
boolean isVIP = true;
if (hasTicket) {
System.out.println("Welcome to the event!");
if (isVIP) {
System.out.println("Please proceed to the VIP area. 🥂");
} else {
System.out.println("Please take a seat in the general area.");
}
} else {
System.out.println("Sorry, you need a ticket to enter. 🚫");
}⚠️ Don't nest too deep! If you have 3+ levels of nesting, your code becomes very hard to read. This is called "pyramid of doom" or "arrow code." Instead, use early returns or combine conditions with &&:
// Instead of nesting:
if (hasTicket && isVIP) {
System.out.println("VIP access granted");
}5️⃣ Switch — Comparing One Value Against Many Options
When you're comparing one variable against many exact values, a switch statement is cleaner than a long if-else-if chain. It's like a vending machine — you press a button (A1, A2, B1), and the machine gives you the matching item.
String day = "Wednesday";
switch (day) {
case "Monday":
System.out.println("Back to work! 💼");
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
System.out.println("Midweek grind 💪");
break;
case "Friday":
System.out.println("TGIF! 🎉");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend! 🏖️");
break;
default:
System.out.println("Not a valid day");
}
// Output: Midweek grind 💪How it works step by step:
- Java evaluates the expression in
switch(day) - It jumps to the
casethat matches the value - It runs the code until it hits a
breakstatement - If no case matches, it runs the
defaultblock (optional but recommended)
6️⃣ The Break Trap — Fall-Through Explained
The #1 bug beginners make with switch is forgetting break. Without it, Java doesn't stop at the matching case — it "falls through" and runs ALL the cases below it too!
// ❌ BUG: Missing break statements!
int num = 1;
switch (num) {
case 1:
System.out.println("One");
// No break! Falls through to case 2...
case 2:
System.out.println("Two");
// No break! Falls through to case 3...
case 3:
System.out.println("Three");
}
// Output: One Two Three (ALL three print!)
// ✅ FIXED: Add break after each case
switch (num) {
case 1:
System.out.println("One");
break; // ← Stops here!
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
}
// Output: One (only the matching case)💡 Java 14+ Enhanced Switch: Modern Java has a new switch syntax that eliminates the break problem entirely:
String result = switch (day) {
case "Monday" -> "Start of week";
case "Friday" -> "TGIF!";
case "Saturday", "Sunday" -> "Weekend!";
default -> "Midweek";
};The arrow -> syntax doesn't need break and can return a value directly.
Try It: Day Planner with Switch
See how switch handles multiple cases and fall-through
// 💡 Try modifying this code and see what happens!
// Day Planner — Java switch simulated in JavaScript
console.log("=== Day Planner ===\n");
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
for (let day of days) {
let plan;
switch (day) {
case "Monday":
plan = "Team meeting at 9am 💼";
break;
case "Tuesday":
plan = "Code review session 💻";
break;
case "Wednesday":
plan = "Lunch & learn 🍕";
brea
...7️⃣ The Ternary Operator — One-Line If/Else
Sometimes you just need to pick between two values based on a simple condition. Writing a full if/else for that feels like overkill. The ternary operator is a one-line shortcut:
// Syntax: condition ? valueIfTrue : valueIfFalse
// Instead of this:
String status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
// You can write this:
String status = (age >= 18) ? "Adult" : "Minor";
// More examples:
int max = (a > b) ? a : b; // Find the bigger number
String label = (count == 1) ? "item" : "items"; // Pluralize
double price = isMember ? 9.99 : 14.99; // Membership discount⚠️ Don't overuse it! The ternary operator is great for simple assignments. But if your logic is complex, use a regular if/else — it's much easier to read and debug. If you're nesting ternaries inside ternaries, that's a code smell.
8️⃣ When to Use If vs Switch vs Ternary
Each control flow tool has its sweet spot. Using the right one makes your code cleaner and easier to read:
| Tool | Best When | Real-World Example |
|---|---|---|
| if / else | 2-3 conditions, especially with ranges | Age verification, input validation |
| else if chain | Multiple range-based conditions | Grade calculator, tax brackets, pricing tiers |
| switch | One variable, many exact values | Menu options, day of week, command parser |
| ternary | Simple A-or-B value assignment | Max value, plural label, discount price |
9️⃣ Real-World Example: Login System
Let's combine everything you've learned into a realistic example. Here's a login system that checks multiple conditions:
String username = "admin";
String password = "secret123";
boolean isAccountLocked = false;
int failedAttempts = 0;
// Step 1: Check if account is locked
if (isAccountLocked) {
System.out.println("🔒 Account is locked. Contact support.");
// Step 2: Check credentials
} else if (username.equals("admin") && password.equals("secret123")) {
System.out.println("✅ Login successful! Welcome, " + username);
failedAttempts = 0; // Reset on success
// Step 3: Wrong password (right username)
} else if (username.equals("admin")) {
failedAttempts++;
System.out.println("❌ Wrong password! Attempts: " + failedAttempts);
if (failedAttempts >= 3) {
isAccountLocked = true;
System.out.println("🔒 Too many attempts. Account locked.");
}
// Step 4: Unknown user
} else {
System.out.println("❌ User '" + username + "' not found.");
}Notice how this uses nested if (the failed attempts check inside the else-if), logical AND (&&), and String comparison with .equals(). This is the kind of real code you'll write in actual applications.
Try It: Ticket Pricing System
Build a complete ticket pricing calculator using if-else, ternary, and switch
// 💡 Try modifying this code and see what happens!
// Ticket Pricing System — Java logic simulated in JavaScript
console.log("=== 🎬 Movie Ticket Pricing ===\n");
// Function to calculate ticket price
function getTicketPrice(age, isStudent, dayOfWeek) {
// Step 1: Free for toddlers
if (age < 3) return { price: 0, label: "Free (toddler)" };
// Step 2: Determine base price by age
let basePrice;
if (age <= 12) {
basePrice = 8; // Child
} else if (age <= 64) {
basePrice
...Common Mistakes Beginners Make
- ❌ Using
=instead of==:if (x = 5) // ❌ This ASSIGNS 5 to x (won't compile for int) if (x == 5) // ✅ This COMPARES x to 5
- ❌ Comparing Strings with
==:if (name == "Alice") // ❌ Compares memory addresses if (name.equals("Alice")) // ✅ Compares actual text content - ❌ Accidental semicolon after if:
if (x > 5); // ❌ This semicolon makes the if do NOTHING { System.out.println("This always runs!"); } - ❌ Forgetting break in switch: Causes fall-through — the code keeps running through the next cases.
- ❌ Writing
if (isValid == true): This works but is redundant. Just writeif (isValid)— it already evaluates to true/false.
Pro Tips
💡 Use early returns to avoid deep nesting. Instead of wrapping everything in if-else, check for the "bad" case first and return early.
💡 Always include default in switch statements — it catches unexpected values and makes debugging easier.
💡 Use constants or enums for switch values instead of "magic strings" — prevents typos and enables auto-complete.
💡 Combine conditions with && and || instead of deeply nesting if statements.
💡 Keep conditions simple — if a condition is complex, extract it into a boolean variable with a descriptive name:
// Hard to read:
if (age >= 18 && hasLicense && !isSuspended && insuranceValid) { ... }
// Easier to read:
boolean canDrive = age >= 18 && hasLicense && !isSuspended && insuranceValid;
if (canDrive) { ... }📋 Quick Reference
| Statement | Syntax | When to Use |
|---|---|---|
| if | if (cond) { } | Single yes/no check |
| if-else | if (cond) { } else { } | Two possible paths |
| else if | if...else if...else | Multiple range-based decisions |
| switch | switch (val) { case: break; } | One variable, many exact values |
| switch (new) | case "x" -> result | Java 14+ — no break needed |
| ternary | cond ? a : b | Simple inline value pick |
🎉 Lesson Complete!
Your programs can now make intelligent decisions! You've learned if-else chains, switch statements, the ternary operator, nested conditions, and when to use each one. You even built a real-world ticket pricing system!
Next up: Loops — learn to repeat actions with for, while, and do-while loops to process data, build patterns, and automate repetitive tasks.
Sign up for free to track which lessons you've completed and get learning reminders.