Card 02/ 09
String Concatenation Example: Adding Numbers Next to Text
1 + 2 + " points" and "points: " + 1 + 2 give two different answers.
+ is evaluated left to right, two operands at a time, and each + picks its job from the two values it has at that moment. So where the text sits in a line decides whether the numbers are added or joined. A label built out of two numbers and a word:
System.out.println(1 + 2 + " points");
System.out.println("points: " + 1 + 2);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.
← → move through sections and cards