自动装箱
编译器调用valueOf(),将基本类型转转换成包装器类对象的操作,即把int转换成Integer,long转换成Long,boolean转换成Boolean等八种基本类型转换成对应的包装器类对象。
自动拆箱
编译器调用intValue(),longValue()等,把Integer,Long,Boolean等8中包装器类对象转换成基本类型,此时,如果包装器类对象为空,会报出npe异常。
什么时候会自动装箱?
1.赋值时
/**
*把基本类型赋值给包装器类时,会进行自动装箱操作
**/
Integer i = 1;
int m = 2;
Integer j = m;
2.方法调用时
//当方法入参是包装器类对象时,传入基本类型会自动装箱
public void do( Integer i){
……
}
//自自动装箱
do(3)
什么时候会自动拆箱?
1.赋值时
把包装器类对象赋值给基本类型变量时,自动拆箱
//把包装器类对象赋值给基本类型变量时,自动拆箱
Integer j = null;
int i = j;
//报异常
2.方法调用时
当方法定义参数是基本类型,传参是包装器对象时,会进行自动拆箱操作
public void testAutoUnBoxing(){
Integer j = null;
doSomeThing(j);
}
private void doSomeThing(int i){
System.out.println(i);
}
3.基本类型与包装器类型比较时
Integer j = null;
int i = 2;
System.out.println(i==j);
System.out.println(i<j);
System.out.println(i>j);
4.运算操作:
两个包装器类型做运算操作时,也会进行自动拆箱操作
Integer j = null;
Integer i = 234;
System.out.println(i+j);