前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 自动拆箱装箱原理

Java 自动拆箱装箱原理

作者头像
王小明_HIT
发布2019-12-18 17:19:31
6940
发布2019-12-18 17:19:31
举报
文章被收录于专栏:程序员奇点程序员奇点

1.需要自动拆箱装箱的类型

2. 基本类型及其包装类型

3.什么是自动拆箱装箱

装箱,就是将基本数据类型转换成包装器类型。

拆箱,就是自动将包装类型转换成基本数据类型

代码语言:javascript
复制
//自动装箱
Integer total = 99;
//自动拆箱
int totalprim = total;

看个栗子

代码语言:javascript
复制
public class StringTest {
    public static void main(String[] args) {
        //自动装箱
        Integer total = 99;
        //自定拆箱
        int totalprim = total;
    }
}

编译Java源码

代码语言:javascript
复制
javac StringTest.java
javap -c StringTest.class

javap 查看汇编命令结果

代码语言:javascript
复制
D:\ideaworkspace\test\src\testtool>javap -c StringTest.class
Compiled from "StringTest.java"
public class testtool.StringTest {
  public testtool.StringTest();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: bipush        99
       2: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: aload_1
       7: invokevirtual #3                  // Method java/lang/Integer.intValue:()I
      10: istore_2
      11: return
}

自动装箱

执行 Integer total =99;

执行代码时系统为我们执行了 Integer total = Integer.valueOf(99);

这个就是自动装箱。

代码语言:javascript
复制
    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

自动拆箱

执行 int totalprism = total 时 系统自动执行了

int totalprim = total.intValue();

代码语言:javascript
复制
/**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
 public int intValue() {
        return value;
 }
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员奇点 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档