AP CSA Unit 1 Day 13: String Concatenation Mixed

Unit 1 Foundation (Cycle 1) Day 13 of 28 Foundation

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.

int x = 3; int y = 4; System.out.println(x + y + " sum"); System.out.println("sum " + x + y);

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).

Review this topic: Section 1.9 — Strings: Concatenation • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.