Search code examples
javastringstring-literals

How many String objects are created on the Heap


I was asked a question in an interview- How many objects are created on the Heap in the following:

String s1= "A";
String s2= "A";
String s3= new String("A");

I answered 1 - because with the new operator only, a string object is created. When the compiler encounters s1, it will simply create "A" on the string literal pool. And s1 and s2 point to the same literal in the literal pool. But the interviewer confused me by saying that where does this pool exists?

Now, in a certain blog, I read:

"In earlier versions of Java, I think up-to Java 1.6 String literal pool is located in permgen area of heap, but in Java 1.7 updates its moved to main heap area."

So in this way, all the 3 string objects are created on the Heap. Isn't it?

But s1 and s2 point to the same literal in the string literal pool(s1==s2 is true), so a separate object shouldn't be created when s2 is encountered. So in this manner, only 2 objects should be created.

Could someone clarify as such how many String objects are created on the Heap? Am I missing something?


Solution

  • The answer is 1. "A" is added to the heap before any of the 3 lines run via the String Pool, which exists in the heap. The first two lines reference those existing values from the string pool. The third line forces the creation of a new object on the heap.

    Here's a great write-up: http://www.journaldev.com/797/what-is-java-string-pool

    Note: I stand corrected on the comment below. The "A" already exists in the thread pool before line 1 ever runs, so nothing is actually added in line 1. Therefore, the net change to the heap is 1 as you said in the interview since only line 3 actually affects the heap.