基于Java中字符串內存位置詳解
前言
之前寫過一篇關于JVM內存區(qū)域劃分的文章,但是昨天接到螞蟻金服的面試,問到JVM相關的內容,解釋一下JVM的內存區(qū)域劃分,這部分答得還不錯,但是后來又問了Java里面String存放的位置,之前只記得String是一個不變的量,應該是要存放在常量池里面的,但是后來問到new一個String出來應該是放到哪里的,這個應該是放到堆里面的,后來又問到String的引用是放在什么地方的,當時傻逼的說也是放在堆里面的,現(xiàn)在總結一下:基本類型的變量數(shù)據(jù)和對象的引用都是放在棧里面的,對象本身放在堆里面,顯式的String常量放在常量池,String對象放在堆中。
常量池的說明
常量池之前是放在方法區(qū)里面的,也就是在永久代里面的,從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";
•第一句代碼執(zhí)行后就在常量池中創(chuàng)建了一個值為holten的String對象;
•第二句執(zhí)行時,因為常量池中存在holten所以就不再創(chuàng)建新的String對象了。
•此時該字符串的引用在虛擬機棧里面。
1.String對象
String a = new String("holtenObj"); String b = new String("holtenObj");
•Class被加載時就在常量池中創(chuàng)建了一個值為holtenObj的String對象,第一句執(zhí)行時會在堆里創(chuàng)建new String("holtenObj")對象;
•第二句執(zhí)行時,因為常量池中存在holtenObj所以就不再創(chuàng)建新的String對象了,直接在堆里創(chuàng)建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
以上這篇基于Java中字符串內存位置詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring MVC接口防數(shù)據(jù)篡改和重復提交
這篇文章主要為大家詳細介紹了Spring MVC接口防數(shù)據(jù)篡改和重復提交,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08使用JWT作為Spring?Security?OAuth2的token存儲問題
這篇文章主要介紹了使用JWT作為Spring?Security?OAuth2的token存儲,大家經(jīng)常使用的方法有兩種一種是使用JWT作為Token傳遞,一種是使用Redis存儲Token,資源服務器本地訪問Redis校驗Token,需要的朋友可以參考下2021-12-12Spring框架中一個有用的小組件之Spring Retry組件詳解
Spring Retry 是從 Spring batch 中獨立出來的一個功能,主要實現(xiàn)了重試和熔斷,對于那些重試后不會改變結果,毫無意義的操作,不建議使用重試,今天通過本文給大家介紹Spring Retry組件詳解,感興趣的朋友一起看看吧2021-07-07