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

Solution 1:

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.

Solution 2:

String s="";

creates no objects.

s+=new String("a");

creates five objects. the new String, the StringBuilder and its char[] and the String resulting and its char[]

s+="b";

creates four objects, the StringBuilder and its char[] and the String resulting and its char[]

So I get a total of nine objects of which are three String objects

Note: You can be sure that "" has already been loaded as it appear in many system classes including ClassLoader and Class.

The Strings "a" and "b" may or may not be considered as new Strings for the purpose of this question. IMHO I wouldn't count them as they will only be created at most once and if this code is only run once, it hardly matters how many strings are created. What is more likely to be useful is to know how many objects are created each time the code is run.