In a simulation for a the OCJP certification I found this question:
1. StringBuffer s1 = new StringBuffer("abc");
2. StringBuffer s2 = s1;
3. StringBuffer s3 = new StringBuffer("abc");
How many objects are created ?
They state that the correct answer is 4 because they state:
s1 is one object, s2 is another object,
s3 is another object and "abc" is another String Object .
But for me it's wrong and it should be 3, because s1
and s2
are the same object. What do you think?
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:
StringBuffer
objects are created when the code is run.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.
Yes definitely 3 Object.both s1 and s2 referring same location. so s1, s2 and "abc" are the objects here. May be it is better not to follow that reference.
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