后增量运算符和前增量运算符之间存在相当混乱,这可以从“算法,罗伯特塞奇威克和凯文韦恩的第 4 版”的摘录中轻松理解
递增/递减运算符:i++ 与 i = i + 1 相同,并且在表达式中具有值 i。类似地,i-- 与 i = i - 1 相同。代码 ++i 和 --i 相同,只是表达式值是在递增/递减之后而不是之前取的。
例如
x = 0;
post increment:
x++;
step 1:
assign the old value (0) value of the x back to x.So, here is x = 0.
step 2:
after assigning the old value of the x, increase the value of x by 1. So,
x = 1 now;
when try to print somthing like:
System.out.print(x++);
the result is x : 0. Because only step one is executed which is assigning
old value of the x back and then print it.
But when, we do operation like this:
i++;
System.out.print(i);
the result is x: 1. which is because of executing Step one at first
statement and then step two at the second statement before printing the
value.
pre increment:
++x;
step 1:
increase the value of x by 1. So, x = 1 now;
step 2:
assign the increased value back to x.
when try to print something like:
System.out.print(++1)
the result is x : 1. Because the value of the x is raised by 1 and then
printed. So, both steps are performed before print x value. Similarly,
executing
++i;
system.out.print(i);
Both steps are executed at statement one. At second statement, just the
value of "i" is printed.