java中( - i + ++ i)中表达式的输出 [英] output of expression in (--i + ++i) in java

查看:255
本文介绍了java中( - i + ++ i)中表达式的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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




执行时的输出:17

决赛i的值是:9

output on execution : 17
The final value of i is : 9

但是根据java中的关联性和优先级规则,我应该首先执行,即从右边执行到左边给出10然后--i给出9 ..加两个,答案应该是19 ...据我所知,这样的代码在C / C ++中给出了未定义的行为,但在java中,规则是严格定义,没有序列点的概念。所以,任何人都可以澄清问题,因为我真的很困惑这个?在一些书中也提到了后增量和后减量运算符是LTR关联的。但是在其他一些书中,它给出了所有增量和减量(post和pre)都是RTL关联的。!!任何人都可以为java提供正确的运算符优先级和关联表吗?

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 ?

推荐答案

你能指出 Java语言中的位置吗?规范它说从右到左的关联性?它不是,它是从左到右(除了多个分配 - 例如 x = y = 4 )。有用地参见JLS部分 15.7.1 标题为首先评估左手操作数。因此答案是正确的:

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

评估第一个 - i 。这会减少 i (现在为8)并返回后减量值(8)。然后将其添加到 ++ i ,这相当于increment-and-get(因此RHS的计算结果为9)。

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).

类似于

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

您是否期望这也被评估rl?

Would you expect this to be evaluated r-l also?

  • Java Operator Precedence
  • Good article on associativity and precedence

这篇关于java中( - i + ++ i)中表达式的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆