内存分配为本地字符串文字? [英] Memory allocation for local String literals?

查看:96
本文介绍了内存分配为本地字符串文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道当我们创建字符串时,它会进入permgenspace。我的问题是,即使字符串文字是方法的本地文件,它是否仍然会存在于jvm的生命周期中。例如,我有下面的代码片段: - $ /

pre $私有静态无效testString1(){
字符串str1 =tetingLiteral ;



private static void testString2(){
String str2 =tetingLiteral;
}

现在从main方法调用

  testString1(); 
testString12();

将str1和str2指向相同的内存位置。



我的理解是他们会引用相同的内存位置(即使在方法内部创建了字符串字面值,它仍会保留jvm的生命期)。但仍然想确认它,因为我无法以编程方式检查它becoz没有办法打印字符串内存位置

解决方案

Java语言规范的第3.10.5节


此外,字符串常量指的是类String的同一个实例。这是因为字符串文字 - 或者更一般地说,是常量表达式(§15.28)的值的字符串 - 被interned,以便使用方法String.intern共享唯一实例。


(请参阅下面的示例,它显示字符串实例在不同包中的类之间起作用。)


I know that when we create string literal, it goes inside permgenspace. My question is will it lie there for the life time of jvm even if that string literal is local to method. For example i have below code snippet:-

private static void testString1(){
        String str1="tetingLiteral";
    }


private static void testString2(){
        String str2="tetingLiteral";
    }

now from main method i call

testString1();
testString12();

will str1 and str2 will refer to same memory location.

My understanding is They will refer to same memory location(even if string literal is created inside method, it will stay there for lifetime of jvm). But still wanted to confirm it as i could not check it programmatically becoz no way to print string memory location

解决方案

From 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.

(And see the example below, which shows that string interning works between classes in different packages, too.)

这篇关于内存分配为本地字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆