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:
- For Loop: Ideal when the number of iterations is known in advance.
- While Loop: Useful when you want to repeat code as long as a condition remains true.
- Do-While Loop: Similar to the while loop, but it guarantees that the code block will execute at least once before the condition is checked.
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
- Logical Errors with Booleans: Confusing the assignment operator
=with the equality operator==is a common source of bugs where the condition always evaluates to true. - Forgetting Break: In
switchstatements, omitting thebreakkeyword causes the program to execute all subsequent cases, which is rarely the desired behavior. - Infinite Loops: Failing to update the loop counter or the condition in a
whileloop can freeze your program.
Try It Yourself
- Write a program that uses a
switchstatement to map a month number (1-12) to its name. - Use an enhanced
forloop to print the squares of each number in an array. - 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);
CodeMaster Academy