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

在《Java程序员面试宝典》里面有提到i++这个部分,j++是一个依赖于java里面的“中间缓存变量机制”来实现的。通俗的说

++在前就是“先加后赋”(++j)

++在后就是“先赋后加”(j++)

 

  
  
  
  
  1. package cn.xy.test;  
  2.  
  3. public class TestPlus  
  4. {  
  5.     private static int a()  
  6.     {  
  7.         int i = 10;  
  8.         int a = 0;  
  9.         a = i++ + i++;  
  10.  
  11.         // temp1 = i; 10  
  12.         // i = i + 1; 11  
  13.         // temp2 = i; 11  
  14.         // i = i + 1; 12  
  15.         // a = temp1 + temp2 = 21;  
  16.         return a;  
  17.     }  
  18.  
  19.     private static int b()  
  20.     {  
  21.         int i = 10;  
  22.         int b = 0;  
  23.         b = ++i + ++i;  
  24.  
  25.         // i = i + 1; 11  
  26.         // temp1 = i; 11  
  27.         // i = i + 1; 12  
  28.         // temp2 = i; 12  
  29.         // b = temp1 + temp2 = 23;  
  30.         return b;  
  31.     }  
  32.  
  33.     private static int c()  
  34.     {  
  35.         int i = 10;  
  36.         int c = 0;  
  37.         c = ++i + i++;  
  38.  
  39.         // i = i + 1; 11  
  40.         // temp1 = i; 11  
  41.         // temp2 = i 11  
  42.         // i = i + 1; 12  
  43.         // c = temp1 + temp2 = 22  
  44.         return c;  
  45.     }  
  46.  
  47.     private static int d()  
  48.     {  
  49.         int i = 10;  
  50.         int d = 0;  
  51.         d = i++ + ++i;  
  52.  
  53.         // temp1 = i; 10  
  54.         // i = i + 1; 11  
  55.         // i = i + 1; 12  
  56.         // temp2 = i; 12  
  57.         // d = temp1 + temp2 = 22;  
  58.         return d;  
  59.     }  
  60.  
  61.     public static void main(String[] args)  
  62.     {  
  63.         System.out.println(a());  
  64.         System.out.println(b());  
  65.         System.out.println(c());  
  66.         System.out.println(d());  
  67.     }  

原帖地址:http://blog.csdn.net/zlqqhs/article/details/8288800

你可能感兴趣的:(java,I)