JVM 字节码之 int 入栈指令

本文转载自JVM 字节码之 int 入栈指令(iconst、bipush、sipush、ldc)

前言

本文介绍 int 入栈指令 iconst、bipush、sipubh、Idc。

当 int 取值 -1~5 采用 iconst 指令,取值 -128~127 采用 bipush 指令,取值 -32768~32767 采用 sipush 指令,取值 -2147483648~2147483647 采用 ldc 指令。

iconst

当 int 取值 -1~5 时,JVM 采用 iconst 指令将常量压入栈中。

定义 Test.java 文件

    public static void main(String[] args) {
        int i = 5;
        int j = -1;
    }

查看 class 文件

  public static void main(java.lang.String[]);
    Code:
       0: iconst_5
       1: istore_1
       2: iconst_m1
       3: istore_2
       4: return

分析 class 文件,int 取值 0~5 时 JVM 采用 iconst_0、iconst_1、iconst_2、iconst_3、iconst_4、iconst_5 指令将常量压入栈中,取值 -1 时采用 iconst_m1 指令将常量压入栈中。

bipush

当 int 取值 -128~127 时,JVM 采用 bipush 指令将常量压入栈中。

定义 Test.java 文件

    public static void main(String[] args) {
        int i = 127;
        int x = 6;
        int y = -2;
        int j = -128;
    }

查看 class 文件

  public static void main(java.lang.String[]);
    Code:
       0: bipush        127
       2: istore_1
       3: bipush        6
       5: istore_2
       6: bipush        -2
       8: istore_3
       9: bipush        -128
      11: istore        4
      13: return

sipush

当 int 取值 -32768~32767 时,JVM 采用 sipush 指令将常量压入栈中。

扫描二维码关注公众号,回复: 11372320 查看本文章

定义 Test.java 文件

    public static void main(String[] args) {
        int i = 32767;
        int x = 128;
        int y = -129;
        int j = -32768;
    }

查看 class 文件

  public static void main(java.lang.String[]);
    Code:
       0: sipush        32767
       3: istore_1
       4: sipush        128
       7: istore_2
       8: sipush        -129
      11: istore_3
      12: sipush        -32768
      15: istore        4
      17: return

ldc

当 int 取值 -2147483648~2147483647 时,JVM 采用 ldc 指令将常量压入栈中。

定义 Test.java 文件

    public static void main(String[] args) {
        int i = 2147483647;
        int x = 32768;
        int y = -32769;
        int j = -2147483648;
    }

查看 class 文件

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #2                  // int 2147483647
       2: istore_1
       3: ldc           #3                  // int 32768
       5: istore_2
       6: ldc           #4                  // int -32769
       8: istore_3
       9: ldc           #5                  // int -2147483648
      11: istore        4
      13: return

参考文献

  1. JVM字节码之整型入栈指令(iconst、bipush、sipush、ldc)
  2. Java bytecode instruction listings

猜你喜欢

转载自www.cnblogs.com/yungyu16/p/13196411.html
今日推荐