String x = new String("xyz");
String y = "abc";
x = x + y;
How many String
objects would get created in this code?
String x = new String("xyz");
String y = "abc";
x = x + y;
How many String
objects would get created in this code?
There will be at least four objects:
"xyz"
"xyz"
string"abc"
x+y
will evaluate to 'xyzabc' .This object will be stored in The String Pool
. And then new String("xyzabc");
will be called resulting in a string object on heap,whose reference is returned to x
. So there are 5 objects. My answer is based on the public String(String original) constructor code
from this reference
Dec 6, 2013 at 12:55
String x = new String("xyz");
There's one: "xyz"
is an interned string.
There's two: new String("xyz")
.
String y = "abc";
There's three: "abc"
is an interned string.
x = x + y;
There's four. Since strings are immutable a third string object must be created: new String("xyzabc")
.
It's possible there could be a fifth object, because the compiler could use a StringBuilder to perform string concatenation.
StringBuilder s = new StringBuilder(x);
s.append(y);
x = s.toString();
char[]
shared between StringBuilder
and String
. It's a nonsense question.
Apr 1, 2013 at 12:58
When the class is loaded, two String objects are created (most likely), one for each String literal. This is a one-time thing ...
Each time the code is run, two Strings are created:
The new String("xyz")
creates a new String whose state is the same as the "xyz"
literal.
The String concatenation x + y
creates a second new String.
It should be noted that String y = "abc";
does NOT create a new String. Rather, it assigns the reference to an existing String to y
. In fact, it is the reference to the String object for the literal that was created when the class was loaded.
Actually, if you drill down, there is going to be a char[]
array created for each of the String objects created. And the String concatenation may involve the creation of a temporary StringBuilder
object. Both of these are implementation details.
It is also possible that loading the class might not result in creation of new String objects. It is true that the String literals will be represented by String Objects in the string pool, however the exact process of how that happens is an implementation detail ... and it doesn't necessarily entail calling String.intern
on a freshly created String object.
And yet another answer is that ZERO objects get created. That is just Java source code, and Java source code doesn't create objects unless you compile it and run it. (Tada!!)
x : as you are using the new keyword and constructor of the class String a String object is created
"abc": is a string literal and Java creates a String object whenever it encounters a string literal.
x : the concatenation of two strings is transformed to StringBuilder.append(X).append(Y).toString(), so another object is created here.