Java之自动装箱与拆箱

自动装箱与拆箱

一:概念

自动拆箱:对象转成基本数值

i = i + 5;//自动拆箱

自动装箱:基本数值转成对象

Integer i = 4;//自动装箱

二:优点与弊端

优点:基本类型和引用类型直接运算

弊端:可能会产生空指针的异常

public class AutoBox {

	public static void main(String[] args) {
		box();
		defaults();
	}
	//装箱与拆箱
	public static void box(){
		//引用类型,引用变量一定指向对象
		//自动装箱,基本数据类型为5,直接变成了对象
		Integer in = 5;     //相当于  Integer in = new Integer(5);
		
		//in是引用类型,不能和基本数据类型运算
		//自动拆箱,引用类型in直接转换成了基本类型
		// in = 7 自动装箱
		in = in + 2;   // in + 2 --->  in.inValue() + 2
		System.out.println(in);
	}
	//空指针的异常
	public static void defaults(){
		Integer in = null;
		in  = in +1;
		System.out.println(in);
	}
}


console:
7
Exception in thread "main" java.lang.NullPointerException

猜你喜欢

转载自blog.csdn.net/mmake1994/article/details/80367033