Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

1.4: String Concatenation

The + operator adds numeric operands and concatenates when either operand is a String. Evaluate equal-precedence + operations from left to right.

College Board Unit 1

How it works

The + operator concatenates when at least one operand is a String, and adds when both operands are numeric. Java evaluates left to right, so the position of the first String in the expression decides whether earlier numbers are added or appended. Any primitive concatenated with a String is converted to its text form, and objects are converted using their toString method.

Read a mixed expression left to right, switching to concatenation from the first String onward.

Common error

An expression beginning with two ints adds them; the same operands after a String are appended as digits.

Worked example

Java

System.out.println(2 + 5 + " points");
System.out.println("points " + 2 + 5);

Output

7 points
points 25

The first line adds before it reaches a String. The second line concatenates from the first operation.

Exercises

1.4.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

System.out.println("A" + (3 + 4) + 2);
Show solution

Output

A72

The parenthesized sum becomes 7; the remaining operations concatenate.

1.4.2 · Write code

Given int correct = 8 and int bonus = 3, print exactly Score: 11. Make the numeric addition happen before concatenation.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

int correct = 8;
int bonus = 3;
System.out.println("Score: " + (correct + bonus));
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic