JAVA / CHAPTER 05
Decisions
BeginnerBuild mutually exclusive branches and safe compound conditions.
By the end of this chapter
- Trace if/else order
- Use short-circuit conditions
- Test boundary values
The idea
An if statement chooses a branch according to a boolean condition. An else belongs to the nearest unmatched if, so braces help communicate the intended structure. In an if/else-if chain, only the first true branch runs. Arrange overlapping conditions deliberately: checking a broad condition first can make a more specific case unreachable. Boundary examples often reveal mistakes that ordinary inputs do not.
The operators && and || short-circuit. Java may skip their right operand once the outcome is known. This supports guards such as checking a reference for null before calling a method. Design the condition from the requirement, then test values just below, at, and above every threshold.
public class Main {
public static void main(String[] args) {
int points = 80;
if (points >= 90) {
System.out.println("gold");
} else if (points >= 70) {
System.out.println("silver");
} else {
System.out.println("practice");
}
}
}silver
The first comparison is false. The second is true, so the remaining alternative is skipped.
Try it yourself
Return a shipping category for weights below 1, from 1 through 5, and above 5; test both boundaries.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING