3

How many objects will be created in the following Java code:

String s = "abc";
s = "";
String s2 = new String("mno");
s2 = "pqr";
trincot
  • 317,000
  • 35
  • 244
  • 286

1 Answers1

3
  1. String s = "abc"; → one object, that goes into the string pool, as the literal "abc" is used;
  2. s = ""; → one empty string ("") object, and again - allocated in the string pool;
  3. 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;
  4. 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:

  1. If corresponding string does not exist, JVM creates a string object and puts it in the string pool. That string object is a candidate to be reused, by JVM, anytime equal to it (again, according to String::equals(..)) string literal is referenced (without explicit new);
  2. If corresponding string exists, its reference is just being returned, without creating anything new.
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66