Chapter 3: Conditional Logic and Control Flow

In programming, control flow refers to the order in which individual statements, instructions, or function calls are executed. By using conditional logic and loops, you transform a static, linear program into a dynamic one that can interact with the user and react to varying data conditions.

1. Decision Making with If-Else

Java’s if-else structure is the primary tool for branching logic. It evaluates a boolean expression—an expression that results in either true or false. If the expression is true, the block of code inside the if statement executes; otherwise, the program moves to the else or else-if blocks.

int temperature = 25;
if (temperature > 30) {
    System.out.println("It's a hot day.");
} else if (temperature > 20) {
    System.out.println("It's a pleasant day.");
} else {
    System.out.println("It's cold.");
}

2. The Switch Statement

When you have a variable that needs to be compared against multiple specific constant values, a switch statement is often cleaner and more readable than a long chain of if-else statements. In Java, the switch statement can work with integers, characters, and even strings (a feature not present in C or C++).

String day = "Monday";
switch(day) {
    case "Monday": System.out.println("Start of the week."); break;
    case "Friday": System.out.println("End of the week."); break;
    default: System.out.println("Just another day.");
}

3. Iteration: For, While, and Do-While Loops

Loops allow your program to perform repetitive actions efficiently. Java provides three main loop types:

4. Advanced: The Enhanced For Loop

Java also features an "enhanced" for loop, also known as the for-each loop. This is the cleanest way to iterate over arrays or collections, as it eliminates the need for manual index management and reduces the risk of index-out-of-bounds errors.

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

Common Beginner Mistakes

Try It Yourself

  1. Write a program that uses a switch statement to map a month number (1-12) to its name.
  2. Use an enhanced for loop to print the squares of each number in an array.
  3. Create a program that keeps asking a user for input until they type "exit."

The switch Expression

Modern Java supports a cleaner switch syntax using arrows, which avoids the need for break statements and reduces bugs from accidental fall-through.

int day = 3;
String name = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Unknown";
};
System.out.println(name);