Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation for local String literals?

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

like image 301
emilly Avatar asked Dec 09 '22 16:12

emilly


1 Answers

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

like image 98
Jon Skeet Avatar answered Dec 11 '22 11:12

Jon Skeet