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. Operators of equal precedence are evaluated from left to right; parentheses and higher-precedence operations are evaluated first. A primitive value concatenated with a String is converted to text. Concatenation creates a String result without changing the original String objects.
Evaluate parentheses and multiplication first, then follow the remaining plus operations left to right, tracking the type of each result.
Common error
Two int operands are added; an int combined with a String is converted to text and appended.
Worked example
Java
System.out.println(2 + 5 + " points");
System.out.println("points " + 2 + 5);Output
7 points
points 25The 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
A72The 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));