How many String objects are created by the following code?
String x = new String(\"xyz\");
String y = \"abc\";
x = x + y;
I have visited ma
The reason that you see different answers to the question is (in part) that it is ambiguous.
"How many String objects are created by the following code?"
The ambiguity is in the phrase "created by the following code":
Is it asking about the number of String objects that are created by (just) the execution of the code?
Or ... is it asking about the number of String objects that need to exist during the execution of the code?
You could argue that the code implicitly creates the String objects that correspond to the literals, not when it is run, but when it is loaded. However, those objects could be shared with other code that uses the same literals. (And if you look hard enough, it is possible that other string objects containing the same character strings get created during the class loading process.)
Another reason you see different answers is that it is not entirely clear how many strings get created. The various specifications state that new String objects will be created at certain points, but there is "wriggle room" on whether intermediate String objects could be created.
For example, the JLS states that new always creates a new object, and that the string concatenation operator creates a new object except under certain clearly specified cases (see my other answer). However, the specs do not forbid creation of other strings behind the scenes.
But in this case, if we assume that we are using a modern Hotspot JVM, then:
new and the + operator) when the code is executed.The existence / creation of these 4 string is guaranteed by the JLS.