JVM 字节码之 int 入栈指令(iconst、bipush、sipush、ldc)

本文详细介绍了Java虚拟机(JVM)处理不同范围内的int类型常量时所使用的四种入栈指令:iconst、bipush、sipush及ldc。针对-1到5之间的数值使用iconst指令;-128到127之间的数值采用bipush指令;-32768到32767之间的数值则使用sipush指令;而-2147483648到2147483647范围内的数值通过ldc指令实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、前言

本文介绍 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 指令将常量压入栈中。

定义 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

转载于:https://juejin.im/post/5b6ea9a75188251b134ea821

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值