AP® Computer Science A · Unit 1 · Topic 1.3
String Concatenation and Console Output
In Java, + means addition between two numbers, but once a String shows up anywhere in the chain, + switches to gluing text together for the rest of the expression read left to right.
Java reads an expression with + strictly left to right, and it decides what + means one operation at a time based on what it has built so far. If both operands at that step are numbers, + adds them. The moment one operand is a String, + concatenates: it turns the other operand into text and joins the characters. That decision doesn't reset partway through a line. Once a String enters the chain, every later + in that same expression concatenates, even if the operands after it look like numbers.
This is why int total = a + b; followed by System.out.println(total + " items"); still does real addition first. total is a plain int variable, computed and stored before println ever runs. Only inside the println call does the + meet a String, so that one addition becomes concatenation with the word items.
println and print both send text to the console, but println adds a line break afterward and print does not. Call print three times in a row and all three outputs sit glued together on one line; call println three times and each one starts fresh on its own line. This matters once you start chaining several output statements, since forgetting which one you used is a common source of console output that looks wrong even though the values themselves are correct.
Key terms
- Concatenation
- Joining a String with another value by converting that value to text and appending its characters.
- Operand
- A value that an operator like + acts on, such as the 2 and 3 in 2 + 3.
- String literal
- Text written directly in code inside double quotes, such as "3".
- println
- A method that prints its argument to the console and then moves to a new line.
- A method that prints its argument to the console without adding a line break afterward.
Watch it explained
- How it worksHow does Java decide whether plus means addition or concatenation as it reads left to right?
- Worked exampleFind what System.out.println(1 + 2 + "3" + 4 + 5); prints to the console.
- How it worksHow does println differ from print when several outputs land on the console in a row?
- Common mistakeWhy isn't the expression "5" + 5 equal to 10?
Check yourself
End of topic.