日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

jvm字符串常量池_java 常量池

發布時間:2023/12/19 综合教程 27 生活家
生活随笔 收集整理的這篇文章主要介紹了 jvm字符串常量池_java 常量池 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

字符串

字符串字面量:就是指這個字符串本身,比如”Java”,”Hello”。

字符串對象:比如new String(“abc”),或者直接String s=”str”,后面的”str”也是一個字符串對象。

字符串引用:引用就是一個變量,指向對應的字符串對象。

常量池

class常量池

Java源文件編譯之后得到的class文件,其中有項信息就是常量池,保存有字面量和符號引用,比如

public class JvmClass1 {

final int b=666;

public static void main(String[] args) {

String c=”java”;

String d=”abcd”;

}

}

對應的class文件中

這一項就是666這個字面量。

這兩項就是java和abcd這兩個字符串的字面量。

而符號引用也是一些常量,比如全限定類名,字段的名稱和描述符,方法的名稱和描述符。

這是類名。

這是變量名。

常量池中有一些常量類型有index屬性,指向另外一個字面量,比如CONSTANT_Class_Info,CONSTANT_String_Info等。

相同的字符串字面量在常量池中只會保存一份,例如

public class JvmClass1 {

public static void main(String[] args) {

String c=”java”;

String d=”abcd”;

String e=”java”;

String f=new String(“java”);

}

}

運行時常量池 && 字符串常量池

class常量池被加載到內存后,形成了運行時常量池,Jdk1.7之前位于方法區中,Jdk1.8之后是放在元空間,或者把元空間看做是新的方法區。

運行時常量池相對于class常量池的一個特點是具有動態性,Java不要求所有常量在編譯器產生,可以在運行時產生常量加入常量池,例如String類的intern()。

String.intern

intern源碼的注解是Returns a canonical representation for the string object.,意思是返回字符串對象的規范表示形式。

第二段是A pool of strings, initially empty, is maintained privately by the class,說的就是字符串常量池,JDK1.6及以前是放在方法區中,后來放到了堆中,其中保存的是字符串對象的引用,而真正的字符串對象實例是在堆中創建。

第三段是

When the intern method is invoked, if the pool already contains a string equal to this {@code String} object

as determined by the {@link #equals(Object)} method, then the string from the pool is returned. Otherwise,

this {@code String} object is added to the pool and a reference to this {@code String} object is returned.

意思是當一個字符串對象調用intern方法,如果池中已經存在值相等(通過String的equal函數比較)的字符串常量,就返回常量池中的常量,也就是堆中對應實例的引用。否則將這個字符串加入常量池。

例如

public class JvmClass1 {

public static void main(String[] args) {

String a = “hello”;

String b = new String(“hello”);

System.out.println(a == b);//false a和b是不同對象

String c = “world”;

System.out.println(c.intern() == c);//true c.intern()返回的就是”world”在常量池中的引用,和c是同一個對象

String d = new String(“mike”);

System.out.println(d.intern() == d);//false d.intern()返回的類似a,而d類似b,不同對象

String e = new String(“jo”) + new String(“hn”);

System.out.println(e.intern() == e);//true 通過拼接得到的,并沒有出現”john”的字面量,所以只有當e.intern()才加入池中,所以是同一對象

String f = new String(“ja”) + new String(“va”);

System.out.println(f.intern() == f);//false 有個博客說”java”在jvm啟動時自動加入字符串常量池中,不過還沒找到其他什么證據。

}

}

總結

以上是生活随笔為你收集整理的jvm字符串常量池_java 常量池的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。