java 建立string對象機制 字串緩衝池 字串拼接機制

來源:互聯網
上載者:User

標籤:[]   字串   als   java   返回   string   int   stringbu   否則   

1.String str = new String("hello");

建立了2個對象,1.檢查常量池中有沒有hello,沒有的話,建立對象放到常量池中,再建立對象放到堆中。如果常量池有hello對象,則只建立一個對象並放到堆中。

2.字串常量池在方法區

3.String str = "hello";檢查常量池有無hello,如果有,則把指向該對象,如果沒有,建立對象放在常量池裡。

4.intern()方法。把字串變成常量池裡的字串:如果常量池中已經包含了等於該String對象的字串,則返回該字串。否則,將該String對象加入常量池,並返回引用。

5.String s1 = "tom";

 String s2 = "cat";

 String s3 = "tomcat";//建立了一個對象,常量池中。

 String s4 = "tom"+"cat";不建立對象

   String s5 = s1 + s2;//建立一個對象"tomcat"

   s3 == s4;true

 s3 == s5;false

 6.1, String s="a"+"b"+"c"+"d"建立了幾個對象(假設之前串池是空的)//建立了一個對象,常量池中
  2,StringBuilder sb = new StringBuilder();
    String a = "a";
    String b = "b";
    String c = "c";
    String d = "d";
    String s = a+b+c+d;  這句話建立了幾個對象//建立了1個String對象,總共建立了3個對象(new StringBuilder(),new char[],new String())
    StringBuilder sb = new StringBuilder();
    sb.append("a").append("b").append("c").append("d");這句話建立了幾個對象//建立0個String對象

 7.字串常量池在方法區中

java 建立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.