简体   繁体   English

前/后自增运算符表达式 Java

[英]Pre/Post Increment operator expression Java

In Java在 Java

int a=10;
a = a + ++a;
System.out.println(a);

it prints 21 .它打印21 I had understood that it would print 22我知道它会打印22

I had understood that since '++' has higher precedence, so it will be calculated first and it will change a's value as it is pre-increment, so increment to variable 'a' would happen there and then...later it should add with a's latest value我已经明白,由于'++'具有更高的优先级,所以它会首先被计算并且它会改变a的值,因为它是预增量的,所以变量'a'的增量会在那里发生,然后......稍后它应该加上 a 的最新值

like below:如下所示:

a = a + 11; // (a is 11 after pre - increment)

so, now a = 11 + 11 = 22 , but program produces o/p = 21 .所以,现在a = 11 + 11 = 22 ,但程序产生o/p = 21

means it is not picking a's latest value which is 11 , and using the old value which was 10意味着它没有选择 a 的最新值11 ,而是使用旧值10

a = 10+ 11 = 21

.. can someone please clear my doubt? ..有人可以解决我的疑问吗?

would appreciate it if the answer contains the concept/reference from any book or java specification如果答案包含任何书籍或 java 规范中的概念/参考,将不胜感激

  • i++ - get and then increment i++ - 获取然后递增
  • ++i - increment and then get ++i - 递增然后得到
  • unary operations (++, !) have the highest priority unary operations (++, !)具有最高优先级
  • expression is evaluated from Left to Right (thanks to user16320675 )表达式从左到右求值(感谢user16320675
int i = 10;
System.out.println(i++);  // 10
System.out.println(i);    // 11
System.out.println(++i);  // 12
System.out.println(i);    // 12

In your example:在您的示例中:

int a = 10;
a = a + ++a; // -> 10 + (10 + 1), from left to right
System.out.println(a);  // 21

From Java docs :来自 Java 文档

All binary operators except for the assignment operators are evaluated from left to right;除了赋值运算符之外的所有二元运算符都是从左到右计算的; assignment operators are evaluated right to left.赋值运算符从右到左求值。

Since a =10, a = 10 + 11 = 21.因为 a =10,所以 a = 10 + 11 = 21。

Why?为什么? Because the value of a is 10, Because You Didn't Increment it yet, it stays at 10.因为 a 的值为 10,因为你还没有增加它,所以它保持在 10。

in ++a, now only you incremented it, then becomes 11. now, a = 10 + 11 is 21.在 ++a 中,现在只有你增加它,然后变成 11。现在,a = 10 + 11 是 21。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM