File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes How Many Objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How Many Objects?" Watch "How Many Objects?" New topic

How Many Objects?

Prash Singh
Ranch Hand

Joined: Aug 23, 2009
Posts: 103

Dear all,

In the following statement how many Objects will be created?

My guess is two.
One is StringBuilder object i.e sb and second is String object "abc".
Am I right?

Please correct me, if I am wrong?

Thanks in Advance.
Pramod P Deore
Ranch Hand

Joined: Jul 15, 2008
Posts: 632

Yes you are right here 2 objects and one reference variable is created.

Life is easy because we write the source code.....
Peter Taucher
Ranch Hand

Joined: Nov 18, 2006
Posts: 174
Question to the pros around: If the internal array 'value' of StringBuilder was recreated in method expandCapacity() would that make it three Objects? Of course, it isn't as the constructor creates a big enough array ... but using the parameterless constructor and then appending a longer String object should result in a new backing array. Would in Java that be considered as Object as well ... or if speaking in term of Objects the internal representations are never minded?

Censorship is the younger of two shameful sisters, the older one bears the name inquisition.
-- Johann Nepomuk Nestroy
David Newton

Joined: Sep 29, 2008
Posts: 12617

Internal representations must be ignored by definition--they're internal, and we wouldn't necessarily have any way of knowing what is or isn't created.

If you create a LinkedHashSet should we count the List that's created? What about objects created for garbage collection management, and so on?
I agree. Here's the link:
subject: How Many Objects?
jQuery in Action, 3rd edition