How many String objects are created by the following code?
String x = new String("xyz");
String y = "abc";
x = x + y;
I have visited many websites where some say that this line of code creates 3 objects and some say it creates 4. I just wanted to know how many objects are created after this line of code is executed.
解决方案
By the end of the run there will be four String objects:
A String that corresponds to the interned "xyz" literal
Its copy created by new String("xyz")
A String that corresponds to the interned "abc" literal
A String that corresponds to concatenation "xyz" + "abc"
The real question is attributing some or all of these objects to your program. One can reasonably claim that as few as two or as many as four Strings are created by your code. Even though there are four String objects in total, objects 1 and 3 may not necessarily be created by your code, because they are in a constant pool, so they get created outside your code's direct control.