Java Essentials: Control Flow and Decisions
Decision Making with if and else
Control flow decides which parts of your program run, how many times they run, and in what order. The simplest decision tool is the if statement. Java evaluates the boolean condition and runs the matching block.
int temperature = 25;
if (temperature > 20) {
System.out.println("Warm day");
} else if (temperature > 10) {
System.out.println("Mild day");
} else {
System.out.println("Cold day");
}The conditions are checked top to bottom, and the first one that evaluates to true wins. You can chain as many else if branches as you need, and the final else catches everything else.
Switching on a Value
When you compare one value against many constants, a switch statement is usually cleaner than a long chain of if blocks.
String day = "Monday";
switch (day) {
case "Saturday":
case "Sunday":
System.out.println("Weekend");
break;
default:
System.out.println("Weekday");
}Notice how two case labels can share the same body, and how break stops the fall-through into the next case. Modern Java also offers switch expressions, which are more concise, but the classic form shown here is still everywhere in existing code.
Repeating Work with Loops
The for loop is best when you know how many times to repeat. The while loop works when you keep going until a condition becomes false.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
int n = 0;
while (n < 3) {
System.out.println("Counting");
n++;
}Every for loop has three parts: an initializer that runs once, a condition checked before every lap, and an update that runs after each lap. Loops can be interrupted with break and skipped to the next lap with continue.
Key Points
- if, else if, and else handle decisions between two or more branches.
- switch matches a value against case constants and uses break to stop fall-through.
- Use for loops for a known count and while loops for a condition-based repeat.
- break exits a loop early and continue jumps to the next iteration.