Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How many string objects will be created by the following code?

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

I had this question at exam. I want to know the right answer . I said 2 objects.
The object from pool that contains "" , "b" and the object created by new String("a");

like image 564
Adi Botez Avatar asked Jun 24 '12 20:06

Adi Botez


2 Answers

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.

like image 58
JB Nizet Avatar answered Sep 28 '22 23:09

JB Nizet


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.

like image 43
Peter Lawrey Avatar answered Sep 29 '22 01:09

Peter Lawrey