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.
The answer is: 2 String objects are created.
So, only 1 object is ever created because Java is pass-by-reference.
By the end of the run there will be four String objects:
String that corresponds to the interned "xyz" literalnew String("xyz") String that corresponds to the interned "abc" literalString 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.
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