i = i++, i = ++i, j = i++, j = ++i 的区别
题目来源牛客网上面练习的一道题目:
检查程序,是否存在问题,如果存在指出问题所在,如果不存在,说明输出结果。package algorithms.com.guan.javajicu; public class Inc { public static void main(String[] args) { Inc inc = new Inc(); int i = 0; inc.fermin(i); i= i ++; System.out.println(i); } void fermin(int i){ i++; } }这个题目正确的答案是0.
原因是:
- Java使用了中间缓存变量机制:
i=i++;等同于:
temp=i; (等号右边的i)
i=i+1; (等号右边的i)
i=temp; (等号左边的i)
而i=++i;则等同于:
i=i+1;
temp=i;
i=temp;
public static void main(String[] args) throws InterruptedException {Inc inc = new Inc();int i = 0;i = i++;System.out.println(i);i = ++i;System.out.println(i);}
public static void main(String[] args) throws InterruptedException {Inc inc = new Inc();int i = 0;int j = i++;System.out.println("i = "+i +" j = "+j);j = ++i;System.out.println("i = "+i +" j = "+j);}
对于j = i++等同于
temp=i;
i=i+1;
j=temp;
对于j = ++i等同于
i=i+1;
temp=i;
j=temp;
i = i++, i = ++i, j = i++, j = ++i 的区别
题目来源牛客网上面练习的一道题目:
检查程序,是否存在问题,如果存在指出问题所在,如果不存在,说明输出结果。package algorithms.com.guan.javajicu; public class Inc { public static void main(String[] args) { Inc inc = new Inc(); int i = 0; inc.fermin(i); i= i ++; System.out.println(i); } void fermin(int i){ i++; } }这个题目正确的答案是0.
原因是:
- Java使用了中间缓存变量机制:
i=i++;等同于:
temp=i; (等号右边的i)
i=i+1; (等号右边的i)
i=temp; (等号左边的i)
而i=++i;则等同于:
i=i+1;
temp=i;
i=temp;
public static void main(String[] args) throws InterruptedException {Inc inc = new Inc();int i = 0;i = i++;System.out.println(i);i = ++i;System.out.println(i);}
public static void main(String[] args) throws InterruptedException {Inc inc = new Inc();int i = 0;int j = i++;System.out.println("i = "+i +" j = "+j);j = ++i;System.out.println("i = "+i +" j = "+j);}
对于j = i++等同于
temp=i;
i=i+1;
j=temp;
对于j = ++i等同于
i=i+1;
temp=i;
j=temp;