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

 

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