public class Change{
private Change(){
}
public static void main (String[]arg){
System.out.println("------------y1-----------");
y();
System.out.println("------------y2-----------");
y2();
System.out.println("------------y3-----------");
y3();
System.out.println("------------y4-----------");
y4();
System.out.println("------------y5-----------");
y5();
}
public static void y(){
int x =1;
int y = x++ + ++x;
System.out.println(y);
System.out.println(x);
}
public static void y2(){
int x =1;
int y = x++;
System.out.println(y);
System.out.println(x);
}
private static void y3() {
int x=1;
int y=x + ++x;
System.out.println(y);
System.out.println(x);
}
public static void y4(){
int x =1;
int y = x++ +1;
System.out.println(y);
System.out.println(x);
}
public static void y5(){
int x =1;
//int y = (x++) + (++x) +( ++x)的字节码和下面的一样
int y = x++ + ++x + ++x;
System.out.println(y);
System.out.println(x);
}
}
输出结果:
------------y1-----------
4
3
------------y2-----------
1
2
------------y3-----------
3
2
------------y4-----------
2
2
------------y5-----------
8
4
y5方法的java字节码指令:
public static y5()V
L0 方法y5内第0行
LINENUMBER 52 L0 //源代码第52行
ICONST_1 //把1压入栈
ISTORE 0 //把栈顶的1存到变量x中
L1
LINENUMBER 53 L1 //源代码第52行
ILOAD 0 //将x变量压入操作栈中,压入的为1 //这两行等同
IINC 0 1 //x+1 //于x++
IINC 0 1 //x+1 //这一行和下一行等同于++x
ILOAD 0 //将x变量压入操作栈,压入的为3
IADD //将操作栈中的两个数出栈再相加,再压回栈 1+3=4
IINC 0 1 //x+1
ILOAD 0 //将x变量压入操作栈,压入的数为4
IADD //将操作栈中的两个数出栈再相加,再压回栈 4+4=8
ISTORE 1 //将栈顶的数出栈再保存到变量y中
L2
LINENUMBER 54 L2
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ILOAD 1
INVOKEVIRTUAL java/io/PrintStream.println (I)V
L3
LINENUMBER 55 L3
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ILOAD 0
INVOKEVIRTUAL java/io/PrintStream.println (I)V
L4
LINENUMBER 56 L4
RETURN
L5
LOCALVARIABLE x I L1 L5 0
LOCALVARIABLE y I L2 L5 1
MAXSTACK = 2
MAXLOCALS = 2
可以看出x++是先把x的值压入栈中再加1,++x是先加1再把值压入栈中,所以y= x++ + ++x + ++x,x刚开始为1,x++后参入运算的值为1,x为2;第1个++x后,x为3,参入运算的值为3;第1个++x后,x为4,参入运算的值为4.即y=1+3+4=8