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?