自动拆箱和封箱
非人为进行转换,称为自动装箱和封箱
public class Test2 {
public static void main(String[] args) {
//装箱:基本数据类型转换为包装类
Integer a = 12;//自动装箱
System.out.println(a);//输出12
//拆箱:包装类类型转换为基本数据类型
int aa = a;//自动拆箱
System.out.println(aa);//输出12
}
}
特点:
基本数据包装类数据类型与基本数据类型进行比对时,基本数据包装类会自动拆箱变为基本数据类型后进行比较
public class Test2 {
public static void main(String[] args) {
int x = 1000;
Integer y = new Integer(1000);//包装类自动变为基本数据类型进行比较
System.out.println(x==y);//输出为true
}
}
包装类数据缓存
Java对经常使用的数据进行缓存,即在第一次创建时缓存数据,后来再次创建会给缓存地址,以便提高效率。
1、Byte、 Short、 Integer、 Long 所对应的包装类的数据缓存范围为-128~127(包括-128和127)
Integer b1 = 127;
Integer b2 = 127;
System.out.println(b1==b2);//输出为true
Integer b1 = 128;
Integer b2 = 128;
System.out.println(b1==b2);//输出为false
2、Float和Double所对应的包装类没有数据缓存范围
Double b1 = 1.0;
Double b2 = 1.0;
System.out.println(b1==b2);//输出为false
3、Char所对应的包装类没有数据缓存范围为0~127
Character b1 = 127;
Character b2 = 127;
System.out.println(b1==b2);//输出为true
4、Boolean所对应的包装类没有数据缓存范围为true和false
Boolean b1 = true;
Boolean b2 = true;
System.out.println(b1==b2);//输出为true