ITPub博客

首页 > IT职业 > IT生活 > java基本类型装箱和拆箱

java基本类型装箱和拆箱

IT生活 作者:ylwtsmt 时间:2021-09-09 09:06:13 0 删除 编辑

Java八种基本数据类型和对应的包装类:
byte----------->Byte
short---------->Short
int-------------->Integer
long------------>Long
char------------>Character
double--------->Double
float------------->Float
boolean-------->Boolean
先看一段代码,TestInte类如下:

public class TestInte{
    public static void main(String[] args){
    int a = 10;
    Integer b = 10;
    int c = b;  
    }

}

编译后对TestInte进行反编译:javap -c TestInte,输出如下:

Compiled from "TestInte.java"
public class TestInte {
  public TestInte();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: bipush        10
       2: istore_1
       3: bipush        10
       5: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       8: astore_2
       9: aload_2
      10: invokevirtual #3                  // Method java/lang/Integer.intValue:()I
      13: istore_3
      14: return
}

装箱:自动装箱和手动装箱,以int为例:通过反编译可以知道其实装箱就是通过Integer.valueOf(int)来实现装箱的

int a = 10;
Integer b = new Integer(a);   //手动装箱
Integer c = a;    //自动装箱

拆箱:手动拆箱和自动拆箱,以int为例,通过反编译可以知道其实拆箱就是通过new Integer(10).intValue()来实现拆箱的

Integer d =  new Integer(10);
int e = d;    //自动拆箱
int f = d.intValue();  //手动拆箱

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4505/viewspace-2799448/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-09

  • 博文量
    81
  • 访问量
    719