AP CSA Unit 1 Day 27: Comprehensive Expression Tracing
Share
Comprehensive Expression Tracing
Section Mixed — Review: All Unit 1
Key Concept
Comprehensive expression tracing combines every Unit 1 skill: identifying types, applying operator precedence, performing casts, evaluating method calls, and tracking string concatenation. The AP exam's most challenging Unit 1 questions layer three or four concepts into a single code segment. Success requires methodical, step-by-step evaluation — writing down intermediate values and types at each stage. Resist the urge to skip steps or evaluate multiple operations simultaneously.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 2.12
Evaluate each part:
n / m: 7 / 3 = 2 (integer division).
n % m: 7 % 3 = 1 (remainder).
Concatenation: Left to right:
• 2 + "." = "2."
• "2." + 1 = "2.1"
• "2.1" + 2 = "2.12"
Output: 2.12
Why Not the Others?
(B) The last value is n / m = 2, not n % m = 1 repeated. The expression ends with (n / m) which is 2.
(C) The middle value is n % m = 1, not n / m = 2. The positions are: quotient, dot, remainder, quotient.
(D) This uses n / m = 3 and n % m = 3, which are both wrong. 7 / 3 = 2 and 7 % 3 = 1.
Common Mistake
In the concatenation chain, each sub-expression in parentheses is evaluated as arithmetic (since both operands are int). Only when the result meets the "." string does concatenation begin. The parentheses force arithmetic evaluation before concatenation.
AP Exam Tip
Parentheses in concatenation expressions force arithmetic first. (n / m) computes the integer result before concatenation. Without parentheses, n / m + "." would still work the same (division before concatenation), but parentheses make the intent clear.