AP CSA Unit 2 Day 4: If Statement
Share
If Statement Execution
Section 2.2 — If Statements
Key Concept
An if statement executes its body only when the condition evaluates to true. Without curly braces, only the next single statement is part of the if body. This is a frequent AP exam trap: indentation does not determine scope in Java. Two indented lines after an if without braces means only the first line is conditional — the second line always executes. Always trace if statements by evaluating the condition first, then determining which code runs.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) B
score = 85. First if: 85 >= 90 is false, so grade stays "C". Second if: 85 >= 80 is true, so grade becomes "B". Both ifs are independent (not else-if), so both are checked.
Why Not the Others?
(A) 85 is not >= 90, so the first if body does not execute.
(C) The second if condition (85 >= 80) is true, so grade is changed from "C" to "B".
(D) Each if assigns grade (replacing the old value), it does not concatenate.
Common Mistake
Two separate if statements are both evaluated independently. If you want only one branch to execute, use if-else if. With separate ifs, a value of 95 would first set grade to "A", then overwrite it to "B".
AP Exam Tip
Watch for sequential if statements vs. if-else if chains. Sequential ifs can cause unexpected overwrites when multiple conditions are true.