-1

Let's consider

int x=1;
int y1 = (x=10) + x;
System.out.println(y1);
// prints 20

x = 1;
int y2 = x + (x=10);
System.out.println(y2);
// prints 11

In the first example, () is executed first as it has the highest precedence; sets x value to 10 and hence the right-hand operand (x) gets the new value 10 and so y1 = 10+10 = 20

In the second example, the left-hand operand 'x' gets its value 1, then () is executed and x gets its new value 10, so y2 = 1+10 = 11;

Why in the 2nd example, () doesn't get executed first; so (x=10) gets executed first and the left-hand operand x should be set to its new value 10 and hence y2 = 20; but it didn't happen this way?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
maanick90
  • 133
  • 1
  • 2
  • 12

2 Answers2

2

I believe the operands are simply evaluated left-to-right. The parentheses in the right-hand operand don't change the fact that the left-hand operand gets evaluated first.

user94559
  • 59,196
  • 6
  • 103
  • 103
  • 1
    Don't believe. Be certain. See [Java Language Specification §15.7 Evaluation Order](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.7): *The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, **from left to right**.* – Andreas Aug 20 '16 at 23:16
0

Maybe it helps to think about int z = f() + g(), i.e. invoking two methods. Why would g() be invoked first? What about int z = f() + (g()) (mind the additional parenthesis)? Left to right is what is happening, where (x=10) is just a construct that - when evaluated - assigns to x and returns 10 to where this construct is used.

C-Otto
  • 5,615
  • 3
  • 29
  • 62