我知道当我们创建字符串文字时,它会进入 permgenspace。我的问题是它是否会在 jvm 的生命周期内存在,即使该字符串文字是方法的本地内容。例如,我有以下代码片段:-
private static void testString1(){
String str1="tetingLiteral";
}
private static void testString2(){
String str2="tetingLiteral";
}
现在从我调用的主要方法
testString1();
testString12();
str1 和 str2 将引用相同的内存位置。
我的理解是它们将引用相同的内存位置(即使字符串文字是在方法内部创建的,它也会在 jvm 的生命周期内保留在那里)。但仍然想确认它,因为我无法以编程方式检查它,因为无法打印字符串内存位置
最佳答案
来自 section 3.10.5 of the Java Language Specification :
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
(请参见下面的示例,该示例表明字符串实习也适用于不同包中的类。)
关于java - 本地字符串文字的内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596694/