不知不觉中,已经写了这么久的java代码,以前太懒了,不爱总结,不爱做记录。现在发现,多多总结还是对自己有很多好处的。好啦,不废话了,今天给大家谈谈这个简单的自增运算问题。
       还记得当初刚开始学习编程语言的时候,就接触到了自增运算符,i++,++i,这字眼你应该是再熟不过了吧。 i++是先赋值后加1, ++i是先加1后赋值。请看下面例子:
Java代码 复制代码
  1. public class test{  

  2.    publi cstaticvoid test(){  

  3.        int count = 0;  

  4.        for(int i = 0; i < 5; i++){  

  5.           count = count++;    

  6.        }  

  7.        System.out.println(count);  

  8.    }  

  9. }  

public class test{
    public static void test(){
        int count = 0;
        for(int i = 0; i < 5; i++){
           count = count++; 
        }
        System.out.println(count);
    }
}


      关于这个例子的结果你怎么看?count=5 ?真的是这样吗?也许还是有不少初学者会认为结果为5。但是运行起来,你会发现结果为0,为什么呢?
       这还得从jvm的运行机制说起,上面的第一次循环是根据以下几步所得:
1. jvm将count的值(初始为0)拷贝到临时变量区
       2. count执行加1,得到count = 1
      3. 返回临时变量区的count值(0)
      4. 将返回的值(0)赋给count,此时count的值仍然为0

      依此,循环5次,所以最终得到的值仍为0。
       这过程就好比如下所示:
Java代码 复制代码
  1. public class test{  

  2.    public staticint test(){  

  3.        //第一步,先保存值到变量区

  4.        int tempCount = 0;  

  5.        //第二步,执行+1

  6.        count = count + 1;  

  7.        //第四部,返回临时变区的变量值

  8.        return tempCount;  

  9.    }  

  10. }  

public class test{
    public static int test(){
        //第一步,先保存值到变量区
        int tempCount = 0;
        //第二步,执行+1
        count = count + 1;
        //第四部,返回临时变区的变量值
        return tempCount;
    }
}

       现在我们再来看看以下代码
Java代码 复制代码
  1. publicclass test{  

  2.    publicstaticvoid test(){  

  3.        int count = 0;  

  4.        for(int i = 0; i < 5; i++){  

  5.           count = ++count;    

  6.        }  

  7.        System.out.println(count);  

  8.    }  

  9. }  

public class test{
    public static void test(){
        int count = 0;
        for(int i = 0; i < 5; i++){
           count = ++count; 
        }
        System.out.println(count);
    }
}

       它的值是什么呢? count=5? 对了! 可通过以上步骤再来分析一次,当执行第一次循环时:
       1. 由于是++count,二话不说,上来先加1,此时count值为1
       2. jvm将count(值为1)拷贝到临时变量区
       3. 返回临时变量区的值(值为1)
       4. 将返回的值赋值给count,因此第一次循环的值为1

       第二次循环,执行此步骤,得到count的值为2,依此类推,循环5次,最终得到的结果为5。
       相信看完这个,你以后应该不会再对这个自加问题犯迷糊了,呵呵,细心,细心,再细心