Why do string additions give different answers?

System.out.println(7 + 5 + " ");

This prints out 12, but in another order

System.out.println(" " + 5 + 7);

it prints out 57. Why is this?

Jon Skeet
people
quotationmark

Firstly, this has nothing to do with System.out.println. You'll see exactly the same effect if you use:

String x = 7 + 5 + "";
String y = " " + 5 + 7;

It's got everything to do with associativity. The + operator is left-associative, so the above two statements are equivalent to:

String x = (7 + 5) + "";
String y = (" " + 5) + 7;

Now look at the results of the first expression in each case: 7 + 5 is just 12, as int... whereas " " + 5 is "5" (a string).

Or to break it down further:

int x1 = 7 + 5;      // 12   (integer addition)
String x = x1 + "";  // "12" (conversion to string, then string concatenation)

String y1 = " " + 5; // "5"  (conversion to string, then string concatenation)
String y = y1 + 7;   // "57" (conversion to string, then string concatenation)

Justification: JLS 15.18 (additive operators):

The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).

people

See more on this question at Stackoverflow