-1

I've seen this question in OCA questions and need to know why it outputs 90 and not 100. Here is the code:

int x = 9;
long y = x * (long) (++x);
System.out.println(y);

So, what I think this would do is, firstly, increment x (because that's what happens at first right?) and then it would do the type promotion and take left x which is 10, turn it into long and multiply those two longs. Right?

user218046
  • 623
  • 6
  • 20

1 Answers1

9

No. The operands of each operator are evaluated from left to right. Therefore the first operand of the * operator, x, is evaluated before the second operand (long) (++x). Therefore 9 is multiplied by 10.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • An example of where precedence doesn't match order of evaluation. +1 – Peter Lawrey Mar 13 '17 at 12:49
  • @Eran, So basically, if Java sees variable in operation - it tries to get its values and write in operation right? from left to right. O.K. I understand now. Thank you Sir. – user218046 Mar 13 '17 at 12:49