Is there a difference between x++ and ++x in java?

后端 未结 16 2438
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:34

Is there a difference between ++x and x++ in java?

16条回答
  •  逝去的感伤
    2020-11-22 03:20

    I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)

    To be accurate (and probably, a bit pedantic),

    int y = 2;
    y = y++;
    

    is compiled into:

    int y = 2;
    int tmp = y;
    y = y+1;
    y = tmp;
    

    If you javac this Y.java class:

    public class Y {
        public static void main(String []args) {
            int y = 2;
            y = y++;
        }
    }
    

    and javap -c Y, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):

    public class Y extends java.lang.Object{
    public Y();
      Code:
       0:   aload_0
       1:   invokespecial  #1; //Method java/lang/Object."":()V
       4:   return
    
    public static void main(java.lang.String[]);
      Code:
       0:   iconst_2 // Push int constant `2` onto the operand stack. 
    
       1:   istore_1 // Pop the value on top of the operand stack (`2`) and set the
                     // value of the local variable at index `1` (`y`) to this value.
    
       2:   iload_1  // Push the value (`2`) of the local variable at index `1` (`y`)
                     // onto the operand stack
    
       3:   iinc  1, 1 // Sign-extend the constant value `1` to an int, and increment
                       // by this amount the local variable at index `1` (`y`)
    
       6:   istore_1 // Pop the value on top of the operand stack (`2`) and set the
                     // value of the local variable at index `1` (`y`) to this value.
       7:   return
    
    }
    

    Thus, we finally have:

    0,1: y=2
    2: tmp=y
    3: y=y+1
    6: y=tmp
    

提交回复
热议问题