College Board Unit 2
How it works
In an if / else if / else chain, Java tests conditions in order and executes only the first branch whose condition is true, skipping the rest entirely. Independent if statements behave differently: each one is tested, so more than one body can run. Without braces, an if controls only the single statement that follows it, and the next line runs unconditionally regardless of indentation.
Trace a classifier at the exact boundary values, not at values comfortably inside each range.
Common error
Writing overlapping conditions in an order where an earlier branch swallows a later one.
Worked example
Java
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("C");
}Output
BThe first condition fails; the second succeeds and skips the final branch.
Exercises
2.2.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
int n = 6;
if (n > 3) n -= 2;
if (n > 3) n *= 2;
System.out.println(n);Show solution
Output
8The first independent if changes n to 4; the second sees that updated value.
2.2.2 · Write code
Given int temperature = 0, print freezing for values at most 0, cool for values from 1 through 15, and warm otherwise.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
int temperature = 0;
if (temperature <= 0) {
System.out.println("freezing");
} else if (temperature <= 15) {
System.out.println("cool");
} else {
System.out.println("warm");
}