關於Java String,你知道多少?

來源:互聯網
上載者:User

一.String s=new String("abc");//產生幾個對象

答案:2個。heap中一個,String pool中一個。

二.String s="abc";

   String s1=new String("abc");//該條語句卻只產生了一個String對象。

三.String s1=new String("abc");

   String s2="abc";

   String s3=new String("abc");

   String s4="abc";

   問題:s1==s2?//false

        s1==s3?//flase

        s2==s3?//false

        s2==s4?//true

4.String hello="hello";

  String hel="hel";

  String lo="lo";

  System.out.println(hello=="hel"+"lo");//true (在編譯階段就能確定)

  System.out.println(hello=="hel"+lo);//false (在運行時才能確定)

 

 

5.String s  = "a" + "b" + "c";產生幾個對象?

很多人會認為是3,4,5個。但實際上僅產生一個對象。在String pool中的"abc"。因為s的值在編譯階段就能確定。

 

總結:java中,String通常分配在兩個地方,一個地方是記憶體堆中,一個是Stirng pool(因為String的通用性而設計的)。弄清楚這兩個方面,問題即迎刃而解。

聯繫我們

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