Java基础面试题(5)----为什么要引入包装数据类型

问题

简单的解释一下什么是Java中的自动拆箱和装箱

解析

Java的八种基本数据类型

他们都有对应的包装数据类型,他们分别是
基本数据类型-----包装数据类型
byte ------Byte
short ------Short
int-----Integer
long----Long
float ----Float
double----Double
boolean----Boolean
char ---- Character

在代码中演示,什么是Java中的拆箱和装箱

public class IntegerTest {

    public static void main(String[] args) {

        //装箱:把基本的数据类型转换成包装数据类型
        //手动装箱
        Integer a = Integer.valueOf(1);
        //自动装箱,实际上实在编译的时候调用了valueOf()的方法
        Integer b=1;


        //拆箱,就是把包装数据类型转化为基本数据类型
        //创建一个包装数据类型
        Integer c = new Integer(3);

        //手动拆箱
        int e = c.intValue();
       //自动拆箱,实际上是在编译时调用intValue();
        int d=c;

    }
}

为什么要引入包装数据类型

Java是一门面向对象的语言,而基本数据类型不具备面向数据的特征,

  • 当我们需要对某些数据进行表达的时候,基本数据类型无法完成,举例说明
public class Test04 {

    static int a;
    static Integer b;

    public static void main(String[] args) {
    
        System.out.println("int基本数据类型的默认值是"+a);
        System.out.println("Integer默认值是"+b);

    }
}

在考试中,我们需要表示考试成绩为零分和没有参加考试的同学的状态,基本数据类型无法满足,因为基本数据类型的默认值为0,而包装数据类型可以使用null来表示没有参加考试的同学,这种功能在MySQL数据库的存储方面非常常见。

  • Integer包装数据类型中缓存了最大值和最小值
 static final Integer cache[];
 .....................
 
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

对于自动装箱的int数据类型,会存在在方法区的缓冲区中保留,再次使用的时候直接引用。这里使用的是通过空间换时间的策略,减少了对象创建的过程,因此,如果是数值相同的Integer类型,地址也相同,代码演示。而new出来的对象,实际的存在于堆中,地址不相同。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42229056/article/details/82914226