StringBuffer sb = new StringBuffer("abc");
StringBuffer sb1 = sb;
StringBuffer sb2 = new StringBuffer("abc");
How many objects are created?
3 Answers 3
- 2
StringBufferobjects are created because there is 2new. - 1
Stringobject is created [JLS, 3.10.5 => It is guaranted that the object will be reused by any other code running in the same virtual machine that happens to contain the same string literal]
answered Jul 30, 2010 at 9:05
Manuel Selva
19.2k22 gold badges97 silver badges143 bronze badges
Sign up to request clarification or add additional context in comments.
9 Comments
andrewmu
What about the
String objects?polygenelubricants
And those objects are backed by
char[], which is an Object, etc.Manuel Selva
Of course, and there is also several Class objects created ;-)
jarnbjo
-1: The original question is actually impossible to answer, since it depends on the implementation of StringBuffer.
Manuel Selva
@jarnbjo I understood the question in a simplest way and my answer is independent form the StringBuffer implementation because I don't mention underlying created char[]. Isn't it ?
|
- 2
StringBufferobjects, each of which will contain achar[] - 1
Stringobject which will contain achar[]
So 6 objects in total.
If any code referencing "abc" has previously been run, then the String won't be created, so only 4 objects will be created.
answered Jul 30, 2010 at 9:16
Jon Skeet
1.5m895 gold badges9.3k silver badges9.3k bronze badges
2 Comments
Jon Skeet
@Visage: It would be hard to implement your own String type, but yes - I'm assuming the normal implementation of StringBuffer too.
pauljwilliams
Its a tad obtuse, yes, but the days are long gone when I could say 'No one would be crazy enough to do that', and beleive it ;)
You could start the debugger and simply count how many times your run over a new ... Advanced: Use https://hat.dev.java.net/ or http://www.eclipse.org/mat/ or other Heap tools.
Comments
lang-java
StringBuildervsStringBufferaspect...