Decrement and assignment operator in java [duplicate]

橙三吉。 提交于 2019-12-25 17:07:46

问题


Can somebody explain why output of the code below is 1.

int i = 1;
i=i--;
System.out.println(i); // 1

回答1:


i-- does the following steps:

  • return the value of i
  • decrement i by 1

so the statement i = i-- does the following:

  • i is returned (the statement now equals i = 1)
  • i is decremented (i is now 0)
  • the statement (the assignment) is now done (i = 1)

In the end i is 1


To make it a bit more clear you could say the line i = i--; does pretty much the same as this code:

int j = i;
i = i-1;
i = j;


来源:https://stackoverflow.com/questions/35132767/decrement-and-assignment-operator-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!