3

I have a below code snippet,

int a = 1,b = 2;
a = b + (b = a); // () have higher precedence, so it should be evaluated first
System.out.println(a); // Output - 3 but should be a = 1 + 1 = 2;

I cannot understand how operator precedence is working here. Since () have higher precedence, it should be implemented first and assign b = 1 and the output should be 2 but its output is 3. Please tell me where I am wrong!

Akki Gupta
  • 149
  • 6
  • 1
    See https://stackoverflow.com/questions/6800590/what-are-the-rules-for-evaluation-order-in-java – MDK Nov 01 '20 at 19:36
  • 1
    `b + (b = a)` is `2 + 1`. The first `b` is evaluated before the assignment `b = a` takes effect (left to right). – ernest_k Nov 01 '20 at 19:37

0 Answers0