java之裝箱拆箱

來源:互聯網
上載者:User

標籤:nbsp   通過   info   ring   ble   裝箱拆箱   構造   lan   對象   

 參考http://how2j.cn/k/number-string/number-string-wrap/22.html

封裝類

所有的基本類型,都有對應的類類型
比如int對應的類是Integer
這種類就叫做封裝類

package digit; public class TestNumber {     public static void main(String[] args) {        int i = 5;                 //把一個基本類型的變數,轉換為Integer對象        Integer it = new Integer(i);        //把一個Integer對象,轉換為一個基本類型的int        int i2 = it.intValue();             }}
Number類

數字封裝類有
Byte,Short,Integer,Long,Float,Double
這些類都是抽象類別Number的子類

package digit; public class TestNumber {     public static void main(String[] args) {        int i = 5;                 Integer it = new Integer(i);        //Integer是Number的子類,所以列印true        System.out.println(it instanceof Number);    }}
基本類型轉封裝類
package digit; public class TestNumber {     public static void main(String[] args) {        int i = 5;         //基本類型轉換成封裝類型        Integer it = new Integer(i);             }}
封裝類轉基本類型
package digit; public class TestNumber {     public static void main(String[] args) {        int i = 5;         //基本類型轉換成封裝類型        Integer it = new Integer(i);                 //封裝類型轉換成基本類型        int i2 = it.intValue();             }}
自動裝箱

不需要調用構造方法,通過=符號自動把 基本類型 轉換為 類類型 就叫裝箱

package digit; public class TestNumber {     public static void main(String[] args) {        int i = 5;         //基本類型轉換成封裝類型        Integer it = new Integer(i);                 //自動轉換就叫裝箱        Integer it2 = i;             }}
自動拆箱

不需要調用Integer的intValue方法,通過=就自動轉換成int類型,就叫拆箱

package digit;  public class TestNumber {      public static void main(String[] args) {        int i = 5;          Integer it = new Integer(i);                  //封裝類型轉換成基本類型        int i2 = it.intValue();                 //自動轉換就叫拆箱        int i3 = it;              }}
int的最大值,最小值

int的最大值可以通過其對應的封裝類Integer.MAX_VALUE擷取

 

應該是自動裝箱必須一一匹配。

但是拆箱,只要拆出來的基本類型,其範圍小於左側基本類型的取值範圍,就可以。

比如:

 Byte b = 5;Short s = 5;Integer i = 5; Long l = 5l;long x;x= b;x=s;x=i;x=l; 

右邊是類類型,左邊的x是long基本類型,那麼也可以自動拆箱。

以x=b為例,b自動拆箱出來時byte基本類型,byte的取值範圍小於long,那麼就不會出現編譯錯誤。

 

java之裝箱拆箱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.