AP CSA Unit 1 Day 13: String Concatenation Mixed
Share
String Concatenation with Mixed Types
Section 1.9 — Strings: Concatenation
Key Concept
Java's Integer and Double wrapper classes allow primitive values to be treated as objects. Autoboxing automatically converts a primitive to its wrapper: Integer x = 5; wraps 5 in an Integer object. Unboxing converts back: int y = x; extracts the primitive value. The AP exam tests edge cases with null — unboxing a null reference throws a NullPointerException. Wrapper classes also provide useful static methods like Integer.parseInt("42") and Integer.MAX_VALUE.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 7 sum sum 34
String concatenation depends on evaluation order (left to right):
Line 3: x + y + " sum" evaluates left to right. First 3 + 4 = 7 (both int, so arithmetic). Then 7 + " sum" = "7 sum" (int + String, so concatenation).
Line 4: "sum " + x + y evaluates left to right. First "sum " + 3 = "sum 3" (String + int, so concatenation). Then "sum 3" + 4 = "sum 34" (String + int, concatenation again).
Why Not the Others?
(B) The first line performs x + y before hitting the String. Since both are int, it is arithmetic addition: 3 + 4 = 7. It only becomes concatenation when the String is reached.
(C) The second line starts with a String, so all subsequent + operations are concatenation. "sum " + 3 produces "sum 3", then "sum 3" + 4 produces "sum 34", not "sum 7".
(D) This reverses both results. The first line adds integers first, the second line concatenates from the start.
Common Mistake
The + operator evaluates left to right. If the left operand is a String (or the result so far is a String), it performs concatenation. If both operands are numeric, it performs addition. The position of the String literal controls which operation happens.
AP Exam Tip
This is one of the most common AP exam tricks. Read + expressions strictly left to right. Once a String appears in the chain, every subsequent + becomes concatenation. To force addition first, use parentheses: "sum " + (x + y).