Memory allocation for local String literals?

2019-06-28 00: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)