1
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?

zeds
  • 137
  • 1
  • 10

2 Answers2

3

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Easy. System.out.println(7 + 5 + " ") is viewed as a mathematical equation, whereas System.out.println(" " + 5 + 7) whereas having the space beforehand, Java (I'm assuming) views it as a string. Thus 'concatenating' the two.

cyclical
  • 395
  • 4
  • 14