自动装箱(autoboxing)和拆箱(unboxing):将基本数据类型和包装类自动转换。
自动装箱
基本数据类型处于需要对象的环境中时,会自动转换:
例如:
public class Test {
public static void main(String[] args) {
Integer t = 5; // 编译器自动转换 Integer t = Integer.valueOf(5);
}
}
自动拆箱
每当需要一个值时,对象会自动转成基本数据类型,没必要再去显示调用:
public class Test {
public static void main(String[] args) {
Integer t = 5;
int j = t; // 编译器自动执行 int j = t.intValue();
}
}
这个过程叫做 自动拆箱;
自动装箱和拆箱的本质
自动装箱和拆箱 的功能实际上是让编译器来帮忙,编译器依据写法,决定是否装箱或者拆箱操作。
包装类空指针异常问题
public class Test {
public static void main(String[] args) {
// 编译正常,但是运行会报错
Integer j = null;
int i = j; // int i = j.intValue() 会报空指针异常
}
}