AP CSA Unit 1 Day 22: Distinct Objects With Same State
Share
Advanced Practice Question
int a = 3;
int b = 4;
System.out.println(a + b + " AP " + a + b);
The + operator is evaluated left to right. Its behavior depends on the types of the operands:
Step 1: a + b → 3 + 4 → 7 (int + int = int arithmetic)
Step 2: 7 + " AP " → "7 AP " (int + String = String concatenation)
Step 3: "7 AP " + a → "7 AP " + 3 → "7 AP 3" (String + int = String concatenation)
Step 4: "7 AP 3" + b → "7 AP 3" + 4 → "7 AP 34" (String + int = String concatenation)
Once a String appears in the chain, everything after it becomes concatenation, not addition.
A) 34 AP 34 — Assumes all + operations are concatenation. The first a + b is int + int, which performs arithmetic addition (7), not concatenation ("34").
C) 7 AP 7 — Correctly gets the left side (7) but incorrectly assumes a + b on the right is also arithmetic. By the time we reach the right side, the left operand is already a String, so each + concatenates: "...3" + 4 = "...34".
D) 34 AP 7 — Gets both sides backward. The left side should add (7), and the right side should concatenate ("34").
The rule is simple but tricky: Java evaluates + left to right. If both operands are numbers, it performs addition. If either operand is a String, it performs concatenation (converting the number to its text form). Once a String enters the chain, every subsequent + is concatenation.
Draw a left-to-right arrow under the expression and evaluate each + one at a time. Label each intermediate result with its type (int or String). The moment the result becomes a String, every + after that is concatenation. To force addition on the right side, use parentheses: "AP" + (a + b).
Keep Building Mastery!
Cycle 2 questions prepare you for the hardest AP CSA exam questions.
Study Games Practice FRQs