且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中关于i++与++i的问题

更新时间:2022-08-14 23:24:23

在《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.csdn.net/zlqqhs/article/details/8288800