[!NOTE] Programs rarely execute straight from top to bottom. You need decision-making logic and repeat logic to build anything useful. Welcome to Control Flow.
IF-Else Statements
The most basic form of decision making. You evaluate a boolean expression, and execute a block of code if it is true.
int speed = 80;
if (speed > 70) {
System.out.println("You are speeding! Ticket issued.");
} else if (speed > 40) {
System.out.println("Good pace. Safe driving.");
} else {
System.out.println("You are driving too slow.");
}
The Switch Statement
If you have many else if conditions checking the same variable against specific, strict values, use a switch block to dramatically improve readability and performance.
int dayOfWeek = 3;
switch(dayOfWeek) {
case 1:
System.out.println("Monday");
break; // Crucial! Prevents "falling through" to the next case.
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Weekend!");
}
Loops: Automating Repetition
When you need to execute the same logic multiple times, use a loop. Java provides several types depending on your needs.
- The For Loop
Use a for loop when you know exactly how many times you want to iterate through a block of code.
// 1. Initialize counter (int i = 0); 2. Check condition (i < 5); 3. Increment (i++)
for (int i = 0; i < 5; i++) {
// This will print 0, 1, 2, 3, 4
System.out.println("Iteration count: " + i);
}
- The While Loop
Use a while loop when the number of iterations is unknown and deeply reliant on a dynamic condition. It checks the condition before running.
int counter = 0;
while (counter < 3) {
System.out.println(counter);
counter++; // If you forget this, the loop runs forever!
}
- The Do-While Loop
A do-while loop is similar to a while loop, but it evaluates its condition at the end of the block instead of the beginning. This guarantees the code block will be executed at least once, even if the condition is false from the start.
int pass = 0;
do {
System.out.println("This runs once no matter what!");
pass++;
} while (pass < 0); // Condition is false, loop terminates after 1 run.
[!CAUTION] Infinite Loops: Always double-check your loop conditions. An infinite
while (true)loop without abreakstatement will freeze your application entirely and cause a catastrophic CPU spike.
Writing Conditions That Stay Readable
Control flow becomes hard when conditions try to do too much in one line. A clean Java program usually gives complex decisions a meaningful name before using them in an if statement.
int age = 21;
boolean hasVerifiedEmail = true;
boolean isEligible = age >= 18 && hasVerifiedEmail;
if (isEligible) {
System.out.println("Account can be activated");
}
This style is easier to debug because you can print or inspect isEligible directly. It also reads closer to the business rule.
Loop Choice Guide
| Need | Use | Example |
|---|---|---|
| Known number of iterations | for | Print 1 to 10 |
| Unknown count, condition-first | while | Read until valid input |
| Run at least once | do-while | Show a menu once before asking again |
| Visit every item | Enhanced for | Print every name in an array |
Guard Clauses
Sometimes it is cleaner to handle invalid cases early instead of nesting multiple levels of if.
static void printDiscount(int age) {
if (age < 0) {
System.out.println("Invalid age");
return;
}
if (age >= 60) {
System.out.println("Senior discount");
} else {
System.out.println("Standard price");
}
}
Common Mistakes
- Using
=instead of==in conditions. - Forgetting
breakin older switch syntax. - Creating infinite loops by forgetting to update the loop variable.
- Writing deeply nested conditions that could be simplified with early returns.
Mini Practice
Write a program that prints grades from marks: 90+ A, 75+ B, 60+ C, otherwise D. Then rewrite it using named boolean variables such as isExcellent and isGood.
Practice Lab: Grade and Eligibility Checker
Use conditions and loops together in one small program.
- Create an array of five marks.
- Loop through each mark.
- Print
Passfor marks 40 and above, otherwiseFail. - Add grade bands: A for 90+, B for 75+, C for 60+, D for 40+.
- Count how many students passed.
Goal: Practice if, else if, comparison operators, and loop repetition in one flow.
Revision Checkpoint
if: Use for boolean decisions.else if: Use for ordered conditions where the first match wins.switch: Use for clear fixed-value branching.for: Use when the iteration count is known.while: Use when repetition depends on a condition.
Before the quiz: Identify whether a problem needs a decision, a counted loop, or a condition-based loop.