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");
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:
""
;"a"
;new String("a")
;s
and the copy of "a"
;"b"
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With