Search code examples
javapre-incrementtype-promotion

Does promotion occur before increment in Java?


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?


Solution

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