Card 02/ 09

ExampleDifficulty: Beginner1 min

Adding Three Things Where One of Them Is Text

A line that builds a label out of two numbers and a word. It produces one of two completely different strings depending on where the word is.

java
System.out.println(1 + 2 + " points");
System.out.println("points: " + 1 + 2);
text
3 points
points: 12

+ is evaluated left to right, two operands at a time. On the first line 1 + 2 is two numbers, so it adds them, and only then meets the string. On the second line the string comes first, so "points: " + 1 is already text, and the 2 joins the end of it.

Nothing here is a special rule about strings. Each + looked at its own two operands and chose a job, and the job the second one chose was decided by what the first one produced.