java输出表达式,java中( - i + ++ i)中表达式的输出

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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值