在Java中存在一些基本數據類型,這些基本數據類型變量,不能像其餘對象同樣調用方法,屬性....java
一些狀況下帶來一些問題,包裝類就是爲了解決這個問題而出現緩存
包裝類可使得這些基礎數據類型,擁有對象的能力測試
拆箱指的是將基礎數據類型包裝爲對象,拆箱與之相反優化
自動裝箱code
將基礎數據類型直接賦值給對應包裝類的引用變量,系統會自動進行裝箱操做對象
Integer a = 10;
自動拆箱blog
Integer a = new Integer(10); int b = a;
手動拆箱繼承
Integer a = new Integer(10); int b = a.intValue();
手動裝箱/裝箱內存
Integer as = new Integer(10);//裝箱 Integer.valueOf(1);//裝箱 Float.valueOf(1.1);//裝箱 .... as.intValue();//拆箱
一般咱們不須要進行手動拆裝箱開發
1.將包裝類型變量直接賦值給對應基礎類型時,系統會自動進行拆箱操做
2.當要訪問這個對象的真實數據值時會進行自動拆箱,例如要輸出對象的值
3.當要對包裝類的實際值進行數學運算時,會自動拆箱,例如比較大小
Integer i1 = new Integer(10); Integer i2 = new Integer(10); System.out.println(i1 == i2); //結果爲false
在開發中常常須要將基礎數據類型與字符串類型相互轉換
//咱們可使用包裝類提供的valueof()方法來將字符串轉爲對象的包裝類 System.out.println(Float.valueOf("1.1ff")); System.out.println(Boolean.valueOf("true")); //相反的String提供了靜態方法valueOf() 其餘任意類型轉換爲字符串類型 Object表示全部類都可,包括包裝類 System.out.println(String.valueOf('c')); System.out.println(String.valueOf(true));
Java虛擬機會默認將一些簡單的字面量對象放到常量池中,來減小頻繁的內存操做;是一種優化機制;
測試代碼:
Long s1 = Long.valueOf(127l); Long s2 = 127l; Long s3 = new Long(127l); System.out.println(s1 == s2); //true System.out.println(s1 == s3); //false String st1 = "常量池噢噢噢噢"; String st2 = "常量池噢噢噢噢"; String st3 = new String("常量池噢噢噢噢"); System.out.println(st1 == st2); //true System.out.println(st1 == st3); //false Boolean b1 = true; Boolean b2 = true; Boolean b3 = new Boolean(true); System.out.println(b1 == b2); //true System.out.println(b1 == b3); //false Character c1 = 'a'; Character c2 = 'a'; Character c3 = new Character('a'); System.out.println(c1 == c2); // true System.out.println(c1 == c3); // false Float f1 = 1.0f; Float f2 = 1.0f; Float f3 = new Float(1.0f); System.out.println(f1 == f2);//flase System.out.println(f1 == f3);//flase Double d1 = 1d; Double d2 = 1d; Double d3 = new Double(1d); System.out.println(d1==d2);//flase System.out.println(d1==d3);//flase
字面量的意思是說,在編譯期間就直接指定了實際值,很是明確的數據
這意味着當咱們沒有使用字面量而是使用 new關鍵字時,對象將直接進入堆區而不會進入常量池 ,請看下面的例子:
Integer a1 = new Integer(10); Integer a2 = new Integer(10); System.out.println(a1 == a2); //false
一旦出現了new 則必然要開闢新內存空間,沒法利用常量池了!所以建議在代碼中儘可能使用字面量避免使用new;
補充說明:
這些包裝類,以及String類提供的靜態方法valueOf();都會先訪問常量池,而不是當即new, 因此使用字面量或者valueOf方法均可以利用常量池;
基礎數據類型不須要緩存到常量池中由於基礎數據類型不存在引用這麼一說,就是一個實際的值隨方法存儲在棧區;