java的装箱和拆箱

                                         java的装箱和拆箱

  Java的数据类型分为三大类,布尔型,字符型和数值型。其中,数值型又分为整形和浮点型。

byte b=18;//1个字节
char ch='a';//2个字节    16位 所以默认值为‘\u0000’一个0四位    
char ch1='男';//2个字节   
float f=12.5f;//4个字节   默认值 0.0f
short sh=20;//2个字节  默认值  0
long o=34L;//L为long 类型的标志,也可小写   8个字节   默认值0
double d=12.45D;//8个字节   默认值0,0d
boolean b1=true;//不确定占几个字节   默认值false

Java的包装类就是可以把简单类型的变量表示成一个类,Java有六个包装类,分别是Boolean,Character,Integer,Long,Float和Double.

下来我们用Int和Integer举例

public class haha {
	public static void main(String[] args){
		 Integer integer=10;//valueOf()装箱
	}
}

查看该类.class文件信息


在执行这段代码时,调用了这个方法。这个就是java的自动装箱。

就是将int型通过这个方法变成Integer类的对象。

 Integer integer2=(Integer)10;//显示装箱
 Integer integer3=new Integer(10);//在堆上分配内存    integer3存储的是一个对象内存地址

装箱过程是通过调用包装器的valueOf方法实现的,而拆箱过程是通过调用包装器的 xxxValue方法实现的。(xxx代表对应的基本数据类型)。

public class haha {
	public static void main(String[] args){
		 Integer integer=10;//valueOf()装箱
		 int i=integer;//拆箱  intValue()方法
		 int i1=(int)integer;//显示拆箱
	}
}

查看该类.class文件信息


执行这段代码时,就调用了intValue()方法,实现了自动拆箱。





为什么这两段代码会执行结果不一样呢,接下来我们分析一下原码

   public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
这个原码可以看出来,在i在最大值127和最小值-128之间,程序会将这个值的引用存在缓存区中,接下来再有i在127~-128之间的值时,就会在缓存区中寻找,并返回缓存区中的地址和值。如果在这个范围外就会重新创建一个对象。


猜你喜欢

转载自blog.csdn.net/qq_37937537/article/details/79775480