Java常量池的一點理解,Java常量池理解

來源:互聯網
上載者:User

Java常量池的一點理解,Java常量池理解
關於網上的一個面試題,求輸出結果:

 
  1. /** 
  2.  *  
  3.  * @author DreamSea 2011-11-19 
  4.  */ 
  5. public class IntegerTest { 
  6.     public static void main(String[] args) {     
  7.         objPoolTest(); 
  8.     } 
  9.  
  10.     public static void objPoolTest() { 
  11.         Integer i1 = 40; 
  12.         Integer i2 = 40; 
  13.         Integer i3 = 0; 
  14.         Integer i4 = new Integer(40); 
  15.         Integer i5 = new Integer(40); 
  16.         Integer i6 = new Integer(0); 
  17.          
  18.         System.out.println("i1=i2\t" + (i1 == i2)); 
  19.         System.out.println("i1=i2+i3\t" + (i1 == i2 + i3)); 
  20.         System.out.println("i4=i5\t" + (i4 == i5)); 
  21.         System.out.println("i4=i5+i6\t" + (i4 == i5 + i6));     
  22.          
  23.         System.out.println();         
  24.     } 
輸出的結果
i1=i2truei1=i2+i3   truei4=i5falsei4=i5+i6true
一些理解: 首先什麼是常量池 ?根據百度的回答,常量池是JVM中的一塊特殊的儲存空間。用於儲存類、介面、方法中的常量以及一些字串常量;當然也可以擴充執行器產生的常量也會放入常量池中。在編譯時間期就已經確定,是已存在的.class檔案中的一部分資料。也就是說,在程式運行還沒有動態輸入資料時,就已經存在了,這樣大大提高了程式運算的效率。
說說以上幾題的原因和Integer 首先 == 兩邊如果是對象,比較的是兩個對象的引用即地址,而不是其值。 i4 跟 i5 是兩個不同的對象 所以輸出falsei1跟i2相等,是因為 Integer中有一塊代碼塊作常量池用,存放-128~127間的常量值, 所以在這之間的每個數不會另外開闢一個地址,也就是說i1和i2是同一個對象,所以 輸出 true第二個 i1==i2+i3 為什麼返回的是 true,那是因為java有拆箱的特性,i1,i2,i3本來都是對象,但是在運算中都先自動轉換成int類型再進行比較,這時候 ==兩邊 比較的是運算值,所以相等 ,第四個 也是一樣道理。
那麼思考 如果是 Integer i1 = 128;   Integer i2 = 128;System.out.println(i1==i2) 會是什麼結果呢?沒錯,程式輸出  false , 因為 128不在Integer的常量池中了。
再來簡單說說String的常量池String s1 = "hello";String s2 = "hello"String s3 = new String("hello");System.out.println( s1 ==s2);System.out.println( s1 ==s3);   會是什麼結果 ? 答案 : truefalse用new String()建立的字串是一個對象不是常量,不能在編譯期就確定,所以new String() 建立的字串不放入常量池中,它們有自己的地址空間。 OK再來一個 
String s4 = "he"+new String("llo");System.out.println( s1 == s4);   
結果 ?答案是  false , 所以只要是在String中new了一下便是一個新的對象了,兩個對象不相等,結果一定是false。






















聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.