Java中字串記憶體位置淺析

來源:互聯網
上載者:User

標籤:==   static   說明   直接   對象   print   obj   常量池   als   

String記憶體位置說明
  1. 顯式的String常量

String a = "holten";String b = "holten";
  • 第一句代碼執行後就在常量池中建立了一個值為holten的String對象;
  • 第二句執行時,因為常量池中存在holten所以就不再建立新的String對象了。
  • 此時該字串的引用在虛擬機器棧裡面。
  1. String對象

String a = new String("holtenObj");String b = new String("holtenObj");
  • Class被載入時就在常量池中建立了一個值為holtenObj的String對象,第一句執行時會在堆裡建立new String("holtenObj")對象;
  • 第二句執行時,因為常量池中存在holtenObj所以就不再建立新的String對象了,直接在堆裡建立new String("holtenObj")對象。
驗證一下
/** * Created by holten.gao on 2016/8/16. */public class Main {    public static void main(String[] args){        String str1 = "高小天";        String str2 = "高小天";        System.out.println(str1==str2);//true                String str3 = new String("高大天");        String str4 = new String("高大天");        System.out.println(str3==str4);//false    }}

返回結果:

truefalse

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.