AP CSA Unit 1 Day 10: Concat Evaluation Order

Unit 1 Advanced (Cycle 2) Day 10 of 28 Advanced

Concatenation Evaluation Order

Section 1.9 — Strings: Concatenation

Key Concept

String concatenation with the + operator follows strict left-to-right evaluation. In 1 + 2 + "abc" + 3 + 4, the first + adds two integers (producing 3), the second concatenates with a string (producing "3abc"), and subsequent operations continue as concatenation (producing "3abc34"). The AP exam uses parentheses to change evaluation order: "abc" + (3 + 4) produces "abc7" because the parenthesized addition happens first. Always evaluate strictly left to right, applying precedence only for parentheses.

Consider the following code segment.

int a = 2; int b = 3; int c = 4; System.out.println(a + b + "" + c); System.out.println("" + a + b + c);

What is printed as a result of executing the code segment?

Answer: (A) 54 234

Left-to-right evaluation with type awareness:

Line 4: a + b + "" + c

2 + 3 = 5 (int + int = arithmetic)

5 + "" = "5" (int + String = concatenation)

"5" + 4 = "54" (String + int = concatenation)

Line 5: "" + a + b + c

"" + 2 = "2" (String + int = concatenation)

"2" + 3 = "23" (concatenation)

"23" + 4 = "234" (concatenation)

Why Not the Others?

(B) The first line adds a + b arithmetically (both int) before hitting the empty String. So the first part is 5, not 23.

(C) The second line starts with a String, so all subsequent + operators are concatenation. a, b, and c are each converted to Strings individually.

(D) Neither line produces 9. The first line sums a + b to get 5, then concatenates. The second line concatenates from the start.

Common Mistake

The position of the empty String "" is the pivot point. Everything to its left that is int + int is arithmetic. Once a String enters the chain, everything after is concatenation. An empty String at the beginning makes everything concatenation.

AP Exam Tip

The empty String trick "" + x converts any value to a String. On the AP exam, watch where the String literal appears in the + chain. That is where the switch from arithmetic to concatenation happens.

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.