3

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

String s = "abc"; s = ""; String s2 = new String("mno"); s2 = "pqr"; 
4
  • What language is this? Add an appropriate tag. Commented Apr 8, 2021 at 6:54
  • Check this answer which describes it using a good diagram that you can remember. The duplicate link there also takes you to very good answers. Commented Apr 8, 2021 at 16:43
  • Also, don't miss this useful comment by JB Nizet and the answer by Stephen C. Commented Apr 8, 2021 at 16:57
  • 1
    Thanks for help @ArvindKumarAvinash Commented Apr 8, 2021 at 17:46

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explanation @GiorgiTsiklauri

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.