How many string objects will be created in memory? [duplicate]

I’ll anwser to another, clearer question: how many String instances are involved in the following code snippet:

String s="";
s+=new String("a");
s+="b";

And the answer is 6:

  • the empty String literal: "";
  • the String literal "a";
  • the copy of the String literal “a”: new String("a");
  • the String created by concatenating s and the copy of "a";
  • the String literal "b"
  • the String created by concatenating s and "b".

If you assume that the three String literals have already been created by previously-loaded code, the code snippet thus creates 3 new String instances.

Leave a Comment