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
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/
how many strings created
yields lots of similar questions. – khelwood