Java中的减量和赋值运算符
问题描述:
有人可以解释为什么下面的代码输出为1。
Can somebody explain why output of the code below is 1.
int i = 1;
i=i--;
System.out.println(i); // 1
答
i- -
执行以下步骤:
- 返回
i $ c的值$ c>
- 递减
i
1
- return the value of
i
- decrement
i
by 1
所以语句 i = i-
执行以下操作:
so the statement i = i--
does the following:
-
i
返回(语句现在等于i = 1
) -
i
递减(i现在为0) - 语句(赋值)现在已完成(
i = 1
)
-
i
is returned (the statement now equalsi = 1
) -
i
is decremented (i is now 0) - the statement (the assignment) is now done (
i = 1
)
最后 i
是1
为了更清楚一点,您可以说 i = i- -;
与以下代码几乎相同:
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;