装箱和拆箱就是基本数据类型和类之间的装换,jdk1.5以后新出的特性
一、自动装箱是什么?
基本数据类型和包装类进行快速转换(底层实则二者通过方法进行相互之间转换)
1.装箱代码实现:
public static void main(String[] args) {
Integer i=12;//int类型装换为Integer类型----------------装箱
System.out.println(i);//输出结果为:12
}
}
输出结果为:12
二、自动拆箱是什么?
包装类—>基本数据类型
1.拆箱代码实现:
public static void main(String[] args) {
Integer i1= new Integer(12);//实例化Integer构造器
int sum=i1;// Integer赋值于int类型-------Integer装换int--拆箱
System.out.println(sum);
}
}
输出结果为:12
三、底层代码案例
1.装箱
valueOf(int i)方法进行底层转换
2.拆箱
拆箱通过实例化 Integer(int value) 有参构造器赋值于final修饰int
Integer类详解文章推荐
链接: https://blog.csdn.net/m0_67929156/article/details/124162285