How many objects will be created in the following Java code:
String s = "abc";
s = "";
String s2 = new String("mno");
s2 = "pqr";
How many objects will be created in the following Java code:
String s = "abc";
s = "";
String s2 = new String("mno");
s2 = "pqr";
String s = "abc";
→ one object, that goes into the string pool, as the literal "abc" is used;s = "";
→ one empty string (""
) object, and again - allocated in the string pool;String s2 = new String("mno");
→ another object created with an explicit new
keyword, and note, that it actually involves yet another literal object (again - created in the string pool) - "mno"
; overall, two objects here;s2 = "pqr";
→ yet another object, being stored into the string pool.So, there are 5 objects in total; 4 in the string pool (a.k.a. "intern pool"), and one in the ordinary heap.
Remember, that anytime you use "string literal"
, JVM first checks whether the same string object (according to String::equals..()
) exists in the string pool, and it then does one of the following:
String::equals(..)
) string literal is referenced (without explicit new
);