aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How many Objects are created ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How many Objects are created ?" Watch "How many Objects are created ?" New topic

How many Objects are created ?

Thiru Mu

Joined: Aug 30, 2007
Posts: 23
StringBuffer s1 = new StringBuffer("abc");
StringBuffer s2 = s1;
StringBuffer s3 = new StringBuffer("abc");
How many objects are created ?
Ravi Ahuja
Ranch Hand

Joined: Nov 13, 2006
Posts: 45

Impossible is Nothing<br />SCJP 1.4: 96%
Thiru Mu

Joined: Aug 30, 2007
Posts: 23
cool..this is what i was expecting...
It was given wrong in the question i have refered..
Jianghu Li

Joined: Sep 01, 2007
Posts: 13
String �abc� is also an "Object".
answer should be 2+1 = 3
If I am wrong, please correct me.
paddy Mahadeva Iyer
Ranch Hand

Joined: Feb 10, 2007
Posts: 63
first line creates an object in heap and also adds it to the string constant pool. The second line juss makes s2 point to s1. here s2 will point to the string "abc" in the constant pool and the third line will create a store abc in a new location in the heap.

So in total my guess is "abc" exists at three places 2 in the heap and the other in the string constant pool.

Now my doubt is only about counting the objects.. what should i count 2/3?? my guess is three.

Somebody please reply abt the count and correct me if any mistake !!
Thiru Mu

Joined: Aug 30, 2007
Posts: 23

Objects can be created using only 'new'

so no confusion the object cunt here is 2....

correct me if i am wrong..
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11477


Strings, and specifically string literals, are handled differently from other objects.

any time you have a new string literal (something in quotes that hasn't been seen before), it is created as a String object in the String Pool.

so, the fact that you have "abc" creates a String object in the pool. having the same literal still gives one object in the pool, so the second "abc" does not create a second String object.

Then, each call of "new StringBuffer()" will give you another object. so, you have the String "abc", and two StringBuffers, each of which has a value of "abc".

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
Thanks Fred for clearing doubt.
Bert Bates

Joined: Oct 14, 2002
Posts: 8883
because of the String constant pool Sun is phasing out questions that ask about how many "String" objects are created - you might get 1 question like this but you probably won't get any.

Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
I agree. Here's the link:
subject: How many Objects are created ?