0

How many String objects'll be created and what would be the string values of those objects

String str1 = new String("test");
String str2 = new String("test");
String str3 = "test";

As per my understanding , Total three objects will be created. Is there any programmatically way to verify how many objects will be created Also on which memory area (STACK,HEAP,STRING POOL)

Idos
  • 15,053
  • 14
  • 60
  • 75
Saurabh Gupta
  • 129
  • 1
  • 2
  • 5
  • 5 objects will be created. When you use new keyword, it will generate 2 objects, one in heap and other in String pool. – Aman jangra May 07 '16 at 11:50
  • New keyword will create objects on heap and String literal will be created on pool. so could you please explain me in details why 5 objects will be created. Any program from which we can verify this behavior. In case newString("test) created two objects then this will be duplication of 'test' in heap as well as in pool. Please correct my understanding on this. – Saurabh Gupta May 08 '16 at 13:29
  • Sorry, my bad, I didn't notice that both are named test. Yes you are right, 3 objects will be create. 2 in heap and one in pool. – Aman jangra May 09 '16 at 05:31
  • In pool, str1,str2,str3 will refer to same literal but in case of heap 2 separate objects will be created. – Aman jangra May 09 '16 at 05:43

0 Answers0