1
votes

How many objects will be created in the following code and where they will be stored?

String s = "abc"; // line 1
String s1 = new String("abc"); // line 2
String str1 = new String("efg"); //line 3
1
3 objects will be created, 1 in SCP and two in heapDeadpool
What would be your best guess and why?PM 77-1
Searching for how many strings created yields lots of similar questions.khelwood
@Deadpool Please excuse me but I don't speak newspeak Does SCP mean "String Constant Pool"?Abra
won't "efg" will also be stored in String Pool ?Ankita

1 Answers

0
votes
Total 3 objects will be created.    
Line 1 : Object will be created in string pool,
Line 2 : Object will be created in Heap,
Line 3 : Object will be created in Heap.

Reason is : 
a) By string literal : Java String literal is created by using double quotes like in line 1. It is always created in String pool,
b) By new keyword : Java String is created by using a keyword “new” like in line 2 and 3.  It is always created in Heap memory.

For reference: https://www.geeksforgeeks.org/string-initialization-java-string-literal-vs-string-object/