Reputation: 157
Let's say we have the following code
String x = new String("xyz");
String y = "abc";
x = x + y;
A friend of mine says that 4 objects are created in total, where I say that only 3 are created. Can someone explain what's going on in the background? I've read about String Literal Pool, but I can find an answer for this.
My explanation for the creation of the 3 object is as follows: one in the String Literal Pool at compile time ("abc"), and two at runtime on the heap ("abc" and x + y)
Upvotes: 0
Views: 216
Reputation: 4520
Yes the code will create 4 objects
String x = new String("xyz"); // object#1 : xyz and Object #2: new String
String y = "abc"; // Object#3 : abc
x = x + y; // object#4 : xyzabc
Upvotes: 0
Reputation: 22973
4 objects are created as follow
// 1. "xyz" in the literal pool
// 2. a new String object which is a different object than "xyz" in the pool
String x = new String("xyz");
// 3. "abc" in the literal pool
String y = "abc";
// 4. new String object
x = x + y;
Upvotes: 2
Reputation: 5423
4 objects will be created.
String are unmodifiable
so every time you concatenate them a new object will be created
in the case of "xyz"
in new String("xyz");
you first create "xyz" object then pass it into a new object (String) so, there are two objects here
new String("xyz") <--there are two objects
"abc" <-- kinda obvious
x + y <-- String are unmodifiable thus this is a new object
Upvotes: 2
Reputation: 1376
Actually.. String pool works when there are same values for both the strings.
For example, if we have String s1="abc" and s2="abc", then both s1 and s2 will point to same memory reference (or an object).
In the above case, 3 objects will be created
for x varible on heap
for y variable on stack
for x+y expression on heap
Upvotes: 0