包装类型与基本类型的区别是什么
我们先来说说int和Integer,boolean和Boolean之间的区别
1,默认值不同,int的默认值为0,boolean的默认值为false,而包装类型都为null;
2,初始化不同 包装类型需要new,基本类型不需要;
3,Int.class是原始类型,Integer.class是对象类型,因此会有成员变量和方法。
所谓的包装类型,就是把基本类型包装在一个类里面做一些事情,体现出面向对象。
我们看到了包装类型,也应该了解下装箱拆箱的概念
自动装箱就是java自动将原始类型转换为对应的对象,比如将int的变量转换为Integer对象,这个过程叫做装箱。反之将Integer对象转换为int类型值,这就叫做拆箱
我们一起来看看自动装箱的代码
public static void main(String[] args) { int i = 10; Integer n = i; }
反编译后为:
public static void main(String args[]) { int i = 10; Integer n = Integer.valueOf(i); }
从反编译所得到的内容我们可以看出,在装箱时候自动调用了Integer的valueOf(int)方法,而在拆箱的时候自动调用了Integer的intVlaue方法。
所以,装箱过程是通过调用包装器的valueOf方法实现的,而拆箱过程是通过调用包装器的 xxxValue方法实现的。