Java: Prefix/postfix of increment/decrement operators?

前端 未结 10 1575
不知归路
不知归路 2020-11-22 07:17

From the program below or here, why does the last call to System.out.println(i) print the value 7?

class PrePostDemo {
     public          


        
10条回答
  •  日久生厌
    2020-11-22 08:00

    Well think of it in terms of temporary variables.

    i =3 ;
    i ++ ; // is equivalent to:   temp = i++; and so , temp = 3 and then "i" will increment and become     i = 4;
    System.out.println(i); // will print 4
    

    Now,

    i=3;
    System.out.println(i++);
    

    is equivalent to

    temp = i++;  // temp will assume value of current "i", after which "i" will increment and become i= 4
    System.out.println(temp); //we're printing temp and not "i"
    

提交回复
热议问题