[!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.