【水 Java基础】i=i++底层解析 2019.12.9

i=i++底层解析

  • i++;
      • 源码
      • i++;字节码
      • i=i++;字节码
      • 字节码反编译

i++;

源码

public class Test {
    public static void main(String[] args) {
        int i = 0;
        i++;
        //i=i++;
        System.out.println(i);
    }
}

i++;字节码

public class Test {
    public Test() {
    }

    public static void main(String[] args) {
        int i = 0;
        int i = i + 1;
        System.out.println(i);
    }
}

表面理解:i++ => i=i+1

i=i++;字节码

//反编译
public class Test {
    public Test() {
    }

    public static void main(String[] args) {
        int i = 0;
        byte var10000 = i;
        int var2 = i + 1;
        i = var10000;
        System.out.println(i);
    }
}

字节码反编译

// i++;
  public static void main(java.lang.String[]);
    Code:
      stack=2, locals=2, args_size=1
         0: iconst_0                          //1.将常量池中常量'int 0'推送至栈顶
         1: istore_1                          //2.将栈顶 'int 0' 存储至局部变量表Slot插槽1中(i)
         
         2: iinc          1, 1                //3.将 i(Solt 1) increment 加1
         
         5: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
         8: iload_1                           //4.加载局部变量表的Solt 1(i)加载到栈顶
         9: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
        12: return
      LineNumberTable:
        line 3: 0
        line 4: 2
        line 5: 5
        line 6: 12
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      13     0  args   [Ljava/lang/String;
            2      11     1     i   I
// i=i++;
  public static void main(java.lang.String[]);
    Code:
      stack=2, locals=2, args_size=1
         0: iconst_0                          //1.栈顶压入 int 0
         1: istore_1                          //2.栈顶 int 0 存入 Solt 1(i) 
         
         2: iload_1							  //3.加载局部变量表的 Solt 1(i = 0) 加载到栈顶
         3: iinc          1, 1				  //4.将 i(Solt 1) increment 加1
         //	iload_1				     		  //  如果,这里再 iload_1 则等式左边的 i 就会刷入1 
         6: istore_1						  //5.栈顶 i = 0 存入 Solt 1(i=1),也就是又刷成 0 
         
         7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
        10: iload_1							  //6.加载局部变量表的 Solt 1(i = 0) 加载到栈顶
        11: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
        14: return
      LineNumberTable:
        line 3: 0
        line 4: 2
        line 5: 7
        line 6: 14
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      15     0  args   [Ljava/lang/String;
            2      13     1     i   I
SourceFile: "Test.java"

实际上,i++ 分两步才能执行完毕的。
i++ =>
tmp = i;,
i = i + 1

解析:i=i++
i = i ++; =>
tmp = i ;,
i=i+1;,
i = tmp

你可能感兴趣的:(Java基础)