在《Java程序员面试宝典》里面有提到i++这个部分,j++是一个依赖于java里面的“中间缓存变量机制”来实现的。通俗的说
++在前就是“先加后赋”(++j)
++在后就是“先赋后加”(j++)
package cn.xy.test;
public class TestPlus
{
private static int a()
{
int i = 10;
int a = 0;
a = i++ + i++;
// temp1 = i; 10
// i = i + 1; 11
// temp2 = i; 11
// i = i + 1; 12
// a = temp1 + temp2 = 21;
return a;
}
private static int b()
{
int i = 10;
int b = 0;
b = ++i + ++i;
// i = i + 1; 11
// temp1 = i; 11
// i = i + 1; 12
// temp2 = i; 12
// b = temp1 + temp2 = 23;
return b;
}
private static int c()
{
int i = 10;
int c = 0;
c = ++i + i++;
// i = i + 1; 11
// temp1 = i; 11
// temp2 = i 11
// i = i + 1; 12
// c = temp1 + temp2 = 22
return c;
}
private static int d()
{
int i = 10;
int d = 0;
d = i++ + ++i;
// temp1 = i; 10
// i = i + 1; 11
// i = i + 1; 12
// temp2 = i; 12
// d = temp1 + temp2 = 22;
return d;
}
public static void main(String[] args)
{
System.out.println(a());
System.out.println(b());
System.out.println(c());
System.out.println(d());
}
}
原帖地址:http://blog.youkuaiyun.com/zlqqhs/article/details/8288800
本文详细解析了Java中的++操作符在不同位置使用时的行为差异,包括先赋后加和先加后赋两种情况,并通过代码实例展示了具体运算过程。

被折叠的 条评论
为什么被折叠?



