Java5.0新特性02-自动装箱与拆箱(Autoboxing/Autounboxing)

自动装箱与自动拆箱:

1.实例一:

class TestDemo 
{
	public static void main(String [] args)throws Exception
	{
		Integer i = 3;  //自动装箱
		int a = i + 3;  //自动拆箱
		System.out.println(a);
	}
}

 测试结果:

6


2.实例二:

class TestDemo 
{
	public static void main(String [] args)throws Exception
	{
		Integer i1 = 3;
		Integer i2 = 3;
		System.out.println(i1==i2);
		
		Integer i3 = 128;
		Integer i4 = 128;
		System.out.println(i3==i4);
	}
}

 测试结果:

true
false

 

注意:

        1.拆箱时需要注意空指针异常(NullPointerException)!

           如:  Integer x=null;
                  int y=x;

       2.包装类的缓存: -128-127

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章