Memory allocation for local String literals?

冷暖自知 提交于 2019-12-23 13:25:17

问题


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


回答1:


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




回答2:


The exact implementation is JVM specific but in Oracle Java 7, the string literals are on the heap and can be cleaned up when no class uses the string literal (as they have been unloaded)



来源:https://stackoverflow.com/questions/15596694/memory-allocation-for-local-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!