Chapter 3: Java Control Flow – Making Decisions and Repeating Tasks
By Ali Naqi • December 23, 2025
🚦 Chapter 3: Control Flow – Making Decisions and Repeating Tasks
1. Decision Making: The if-else Statement
The if statement is the most fundamental way to control the flow of your program. It tells Java: "Only execute this block of code if this specific condition is true."
The Basic Syntax
Java
if (condition) {
// code to run if condition is true
}
Adding an Alternative: else and else if
What if the condition is false? You can use else to provide a backup plan. If you have multiple specific conditions, you use else if.
Example: A Simple Weather App
Java
int temperature = 28;
if (temperature > 30) {
System.out.println("It's a hot day! Stay hydrated.");
} else if (temperature >= 20) {
System.out.println("The weather is perfect for a walk.");
} else {
System.out.println("It's a bit chilly; grab a jacket.");
}
The "One-Line" Trap: If your if statement only has one line of code, Java doesn't strictly require the curly braces { }. However, always use them anyway. It prevents bugs later when you decide to add a second line to that block and forget that the braces were missing.
2. The switch Statement: The Clean Alternative
If you find yourself writing ten else if statements to check the same variable (like checking which day of the week it is), your code starts to look like a "ladder" that is hard to read. This is where the switch statement shines.
A switch is like a multi-way branch. It looks at a single variable and jumps to the "case" that matches.
Java
int dayOfWeek = 3;
switch (dayOfWeek) {
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("Invalid day");
break;
}
The Crucial break Keyword
In a switch block, the break statement is vital. If you forget it, Java will perform "fall-through." It will execute the matching case and then keep executing every case below it until it hits a break or the end of the block.
- Modern Java Tip: Since Java 12, there is a "Switch Expression" that uses arrows (->) and doesn't require break keywords. It’s much cleaner, but it’s good to learn the traditional way first as you’ll see it in most existing codebases!
3. The Power of Repetition: Loops
Computers are famous for one thing: they never get bored. They can perform the same calculation a billion times without making a single "tired" mistake. We use loops to handle these repetitive tasks.
A. The while Loop (The "Check First" Loop)
The while loop repeats a block of code as long as a condition remains true. It checks the condition before running the code.
Java
int energyLevel = 5;
while (energyLevel > 0) {
System.out.println("Working... Energy is at " + energyLevel);
energyLevel--; // Don't forget to change the condition, or it runs forever!
}
B. The do-while Loop (The "Act First" Loop)
This is almost identical to the while loop, except it checks the condition after the code runs. This guarantees that the code block will execute at least once.
Java
int count = 10;
do {
System.out.println("This will print even though the condition is false.");
} while (count < 5);
C. The for Loop (The "Counter" Loop)
The for loop is the most common loop in Java. It’s perfect when you know exactly how many times you want to repeat something. It packs the initialization, the condition, and the update all into one line.
Java
// (initialize; condition; update)
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration number: " + i);
}
Breakdown of the for loop:
- int i = 1: We create a counter variable.
- i <= 5: The loop continues as long as this is true.
- i++: After every loop, we add 1 to i.
4. Branching: break and continue
Sometimes you need to interrupt a loop while it’s running.
- break: This kills the loop entirely and jumps to the code immediately after the loop.
- continue: This skips the rest of the current turn and jumps straight to the next iteration (the next "increment" step).
Example:
Java
for (int i = 1; i <= 10; i++) {
if (i == 5) continue; // Skip the number 5
if (i == 8) break; // Stop the whole loop at 8
System.out.print(i + " ");
}
// Output: 1 2 3 4 6 7
5. Practical Logic: Nesting and Complex Conditions
You can put loops inside loops, and if statements inside loops. This is called nesting.
Imagine you are printing a grid for a game (like Tic-Tac-Toe). You need an outer loop for the rows and an inner loop for the columns.
Java
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print("[ ] ");
}
System.out.println(); // Moves to a new line after each row
}
Combining Conditions with Logical Operators
From Chapter 2, remember && (AND) and || (OR)? They are the secret sauce of control flow.
Java
if (hasTicket && (isVip || age >= 18)) {
System.out.println("Access granted.");
}
6. Common Pitfalls for Beginners
- The Infinite Loop: This happens when your loop condition never becomes false. If your program suddenly freezes and your laptop fan starts screaming, you probably forgot to increment your counter (e.g., forgot i++).
- The Off-By-One Error: This is a classic. You want a loop to run 10 times, but it runs 9 or 11 because you used < 10 instead of <= 10. Always double-check your boundaries.
- Using == with Strings: This is a very common Java mistake. To compare numbers, use ==. To compare Strings, you must use .equals().
- Bad: if (name == "Admin")
- Good: if (name.equals("Admin")) (We will explore why in the next chapter on Strings and Objects!)
- Bad: if (name == "Admin")
🛠️ Putting it All Together: The "Guess My Number" Game
Let’s combine everything we've learned into a small, interactive logic snippet. Imagine the computer has picked the number 7.
Java
int secretNum = 7;
int userGuess = 0;
int attempts = 0;
System.out.println("I'm thinking of a number between 1 and 10...");
while (userGuess != secretNum) {
userGuess++; // Simulating a user guessing 1, then 2, then 3...
attempts++;
if (userGuess < secretNum) {
System.out.println(userGuess + " is too low!");
} else if (userGuess > secretNum) {
System.out.println(userGuess + " is too high!");
} else {
System.out.println("Correct! It took " + attempts + " tries.");
}
}
📝 Chapter Summary
In this chapter, we mastered the "steering wheel" of Java:
- if, else if, and else for basic decision making.
- switch for handling multiple specific cases cleanly.
- while and do-while for loops where the number of repetitions is unknown.
- for loops for precise, counted repetitions.
- break and continue for fine-tuning loop behavior.
You now have the tools to build logic. Your programs can react to data, make choices, and process large amounts of information through loops.
But as your programs grow, you'll find that managing a "wall of code" in one single main method becomes a nightmare. How do we organize our code into reusable pieces?