關於Java的一些小知識

來源:互聯網
上載者:User

標籤:sys   有一個   16px   post   輸出   out   關於   blog   類型轉換   

一、對於java變數 的存放

一般的變數存放在棧、堆、和記憶體池裡面。用new聲明出來的,一般放在堆記憶體中。而一些基本類型的變數和對象的引用變數都是在函數的棧記憶體中分配。對於常量池,像我們通常的String s1="abc";這樣聲明的字串對象就是儲存在常量池中。

String s1="abc";String s2="abc";String s3=new String("abc");System.out.println(s1==s2);System.out.println(s1==s3);

這樣輸出的結果是true和false。

 

二、Integer和int的比較

1 Integer a=new Integer(128);2 int b=128;3 Integer c=new Integer(6);4 Integer d=new Integer(6);5 System.out.println(a==b);6 System.out.println(c==d);

輸出的結果是true和false

int是基礎資料型別 (Elementary Data Type),而Integer是對象,用一個引用指向一個對象。

int 跟 Integer之間有裝箱跟拆箱的方法:

裝箱:

//裝箱Integer num=1; //將基礎資料型別 (Elementary Data Type)轉換為對象

拆箱:

//裝箱Integer num=1;//拆箱int num1=nun; //將對象轉換為基礎資料型別 (Elementary Data Type)

另外一點:

對於Integer裝箱時的值,Java定義從-128到127之間的數,被裝箱為Integer對象後,被存在記憶體中被重用,而且始終只有一個這個值的對象。

如果數值超過128或小於-127,就會new一個新的Integer對象。

Integer a=128;Integer b=128;Integer c=127;Integer d=127;System.out.println(a==b);  //結果falseSystem.out.println(c==d);  //結果ture

 

關於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.