You are right that the answer is not 4 objects.
However, the question "how many objects are created" is ambiguous. The issue is that one of the three objects is not created when you execute the code. Specifically, the String
object that corresponds to the "abc"
literal is actually created when the code is loaded. When that code is executed, two StringBuffer
objects are created, and the pre-existing String
object is used.
And in fact it is more complicated than that, since at class load time it is possible that another temporary String
object is created and then discarded after it has been interned;
If an "abc"
literal has already been loaded in a different class, then that one will be used.
It is not specified if the string pool implementation makes a fresh copy of the String
if it needs to put it into the pool.
Unless the question is more precisely stated, there is no single correct answer. The best you can say is:
- Two
StringBuffer
objects are created when the code is run.
- One or two
String
objects are created when the code is loaded.
Then there is the issue of whether you should count the private char[]
objects that form part of the StringBuffer
and String
objects. That could inflate the object count to as much as 8.