Java中字符串存儲在JVM的哪部分?

原文鏈接:https://www.cnblogs.com/holten/p/5782596.html

現在總結一下:基本類型的變量數據和對象的引用都是放在棧裏面的,對象本身放在堆裏面,顯式的String常量放在常量池,String對象放在堆中。

常量池的說明

常量池之前是放在方法區裏面的,也就是在永久代裏面的,從JDK7開始移到了堆裏面。這一改變我們可以從oracle的release version的notes裏的** Important RFEs Addressed in JDK 7 **看到。

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.
RFE: 6962931

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
    }
}

返回結果:

true
false
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章