int i=9;
System.out.println(--i + ++i);
output on execution : 17
The final value of i is : 9
But according to associativity and precedence rules in java,, ++i should be executed first i.e from Right to left which gives 10 and then --i gives 9 .. adding both,, the answer should be 19... As far as i have known such a code gives undefined behaviour in C/C++ but in java ,, the rules are strictly defined and there is no concept of sequence points. So, can anyone clarify the problem as iam really confused about this ?? Also in some books it was mentioned that post increment and post decrement operators are LTR associative. But in some other books it's given all increment and decrement(both post and pre) are RTL associative..!! Can anyone give a correct operator precedence and associativity table for java ?
解决方案
Can you point to where in the Java Language Specification it says that associativity in right-to-left? It is not, it is left to right (with the exception of multiple assigments - e.g. x = y = 4). See JLS section 15.7.1, helpfully titled "Evaluate Left-Hand Operand First." Hence the answer is correct:
--i + ++i
First --i is evaluated. This decrements i (which is now 8) and returns the post-decrement value (8). This is then added to ++i which is equivalent to increment-and-get (so the RHS evaluates to 9).
It's similar to
AtomicInteger i = new AtomicInteger(9);
i.decrementAndGet() + i.incrementAndGet();
Would you expect this to be evaluated r-l also?