java - 本地字符串文字的内存分配?

标签 java string memory garbage-collection

我知道当我们创建字符串文字时,它会进入 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/

相关文章:

java - Heroku + Spring Boot : @Scheduled not running at correct times

linux - android linux内核中的虚拟地址到物理地址和反向

c++ - 对内存中同一地址的写入之间可能存在数据竞争

ios - 从 libBacktraceRecording.dylib 连续分配 500kb

java - 发送 Intent 对象

java - 将 WAR 文件上传到 WebSphere 6.1 时出现问题

java - 使用流更改 ArrayList 中对象字段的值,使代码更高效

sql - 仅选择数值,否则返回 NULL

python - 如何使用 Pandas 交换列中的两个(字符串)值

java - 如何使用 Java Stream 逐行读取文件