Output of expressions in Java (– I)

int i=9;
int i=9;
System.out.println(--i + ++i);

But according to the association and priority rules in Java, I should execute first, that is, execute 10 from right to left, and then – I gives 9 Adding both, the answer should be 19... As far as I know, such code gives undefined behavior in C / C + +, but in Java, the rules are strictly defined and there is no concept of sequence points So anyone can clarify the problem because I'm really confused about this? Some books mention that the post increment and post decrement operators are associated with LTR But in other books, it shows that all increments and decrements (post and pre) are RTL related!! Can anyone provide java with the correct operator precedence and association tables?

Solution

Can you point out where it says right to left relevance in the Java language specification? It's not, it's left to right (except for multiple assignments – e.g. x = y = 4) Refer to JLS section 15.7 Section 1, entitled "evaluate left-handed operands first" So the answer is correct:

--i + ++i

Evaluate first – I. This decrements I (now 8) and returns the post impairment (8) Then add it to I, which is equivalent to increment and get (so the calculation result of RHS is 9)

It is similar to

AtomicInteger i = new AtomicInteger(9);
i.decrementAndGet() + i.incrementAndGet();

Do you expect this to be R-L evaluated?

>Java operator precedence > good article about dependencies and priorities

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>