0
StringBuffer sb = new StringBuffer("abc");
StringBuffer sb1 = sb;

StringBuffer sb2 = new StringBuffer("abc");

How many objects are created?

5
  • 3
    It's a trick question: None, as this will result in a compilation error (missing semicolon) :) Commented Jul 30, 2010 at 9:10
  • @ Tomas You are right ;-) How can we edit questions ? We need at least a given reputation, how much ? Commented Jul 30, 2010 at 9:13
  • 1
    @vijay: Instead of asking what is frankly a rather "shallow" question (in terms of instructional values), you should perhaps say what is it that you want to learn from all this. Then we can address the issue in more general terms rather than this specific snippet (which doesn't demonstrate much in terms of how shared references/string interning/etc work if that's your real issue). And then there's the whole StringBuilder vs StringBuffer aspect... Commented Jul 30, 2010 at 9:19
  • @Manual Selva :Sorry , I forgot to write semicolon. Commented Jul 30, 2010 at 9:31
  • @polygenelubricants : I just wanted to know the how StringBuffer works. I was checking some documents and got this question. Commented Jul 30, 2010 at 9:34

3 Answers 3

4
  • 2 StringBuffer objects are created because there is 2 new.
  • 1 String object 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]
Sign up to request clarification or add additional context in comments.

9 Comments

What about the String objects?
And those objects are backed by char[], which is an Object, etc.
Of course, and there is also several Class objects created ;-)
-1: The original question is actually impossible to answer, since it depends on the implementation of StringBuffer.
@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 ?
|
1
  • 2 StringBuffer objects, each of which will contain a char[]
  • 1 String object which will contain a char[]

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.

2 Comments

@Visage: It would be hard to implement your own String type, but yes - I'm assuming the normal implementation of StringBuffer too.
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 ;)
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.