0

currently I am preparing for OCAJP exam, I got a similar question following like this, the explanation which is given is not satisfactory. problem:

// some code

int a=2;
int c=6;
int v=a+c*(a=3);
System.out.println(v);

Why v is printed as 20, not 21? as I know (*) operator will evaluates first.but here it is evaluates from left to right rule. also (a=3) is in parenthesis,so anyhow it should evaluates first.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 2
    Through operator precedence, `c` and `(a=3)` are determined to be operands of `*`. The result of that and `a` are determined to be the operands of `+`. Then evaluation begins from the left. `a` is evaluated and produces `2`. Then `c*(a=3)` is evaluated. `c` produces `6` and `(a=3)` sets `a` to `3` and produces `3`. `6*3` produces `18` and `2+18` produces `20`. – Sotirios Delimanolis Feb 15 '18 at 00:42
  • A relevant comment from the dupe link is *The idea that the entire thing in parentheses is evaluated first is simply false, so stop believing that.* – Scary Wombat Feb 15 '18 at 00:47
  • thank you so much guys , now I got it. – Anirban95 Feb 15 '18 at 00:54

0 Answers0