java中的自動裝箱和自動拆箱

來源:互聯網
上載者:User

標籤:auto-boxing auto-uboxing

/*JDK5.0新特性:以下的特性適合JDK1.5版本之後的。包括1.5jdk1.4,包括1.4在內之前的所有版本不能使用以下特性。自動裝箱(auto_boxing)和自動拆箱(auto_unboxing)*/public class IntegerTest05{public static void main(String[] args){//JDK5.0之前的.//int-->Integer (裝箱)Integer i1 = new Integer(10);//Integer-->int (拆箱)int i2 = i1.intValue();//JDK5.0之後,包括5.0Integer i3 = 10; //自動裝箱int i4 = i3; //自動拆箱System.out.println(i3); //"10"System.out.println(i4+1); //11//JDK5.0之後m1(321); //自動裝箱.System.out.println(m2(10,5) + 1); //自動裝箱}public static void m1(Object o){System.out.println(o);}public static int m2(Integer i1,Integer i2){return i1 - i2; //自動拆箱}}//深入瞭解自動裝箱和自動拆箱/*深入自動裝箱和自動拆箱:1.自動裝箱和自動拆箱是程式編譯階段的一個概念,和程式運行無關。2.自動裝箱和自動拆箱主要目的是方便程式員編碼。*/public class IntegerTest06{public static void main(String[] args){Integer i1 = new Integer(10);Integer i2 = new Integer(10);//這裡不會有自動拆箱System.out.println(i1==i2); //false//比較兩個Integer類型的資料是否相等,不能用"=="//Integer已經重寫了Object中的equals方法.System.out.println(i1.equals(i2)); //true//重點:Integer i3 = 128;Integer i4 = 128;//上面的等同於//Integer i3 = new Integer(128);//Integer i4 = new Integer(128);System.out.println(i3==i4); //false//注意以下程式.//如果資料是在(-128~127)之間,java中引入了一個“整型常量池”,在方法區中。//該整型常量池只儲存-128~127之間的資料。Integer i5 = 127; //這個程式不會在堆中建立對象,會直接從整型常量池中拿.Integer i6 = 127;System.out.println(i5==i6); //trueInteger i7 = -128;Integer i8 = -128;System.out.println(i7==i8); //trueInteger i9 = -129;Integer i10 = -129;System.out.println(i9==i10); //false}}


本文出自 “gaogaozi” 部落格,請務必保留此出處http://hangtiangazi.blog.51cto.com/8584103/1662493

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.