3 or 4, depending on implementation. Some compilers would create only one String object for the constant "abc" and reference it as many times as necessary, and other compilers would create one object per constant. AFAIK, this has not been mandated by all the languages specification versions, and it could change again in the future.
Or more, depending on StringBuffer's implementation (which could actively create a char[] and copy the initialization String, as opposed to a lazy implementation that postpones this until the StringBuffer's contents are really changed). Again, this should not be mandated by the language. And, BTW, do arrays count as Object
s for the purpose of the question? And what if a StringBuffer implementation stored information in a JNI structure? What that count as objects? I'm just trying to re-inforce my point about non-language-mandated implementation details.
A test should not ask this kind of questions unless it is about a specific implementation and/or JLS version.
What is absolutely clear is that the reason they give for their answer of 4 is completely incorrect. The assignment to s2
does not cause any new object to be created.