• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object creation??

 
Harvinder Singh
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How many objects are created by the following code and explain
why?
1.StringBuffer s1= new StringBuffer("abc");
2.StringBuffer s2= s1;
3.StringBuffer s3= new StringBuffer("abc");
//Is it 2??
 
Jayant Kulkarni
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Yes it will create only 2 objects, since you specify two times the "new" operator.
s2=s1 will assign the previous reference and will not create any new object.
Thanks,
Jayanta
 
Jim Crawford
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would count the new's, so on face value it would seem like two, except if you are counting the string literal, which technically I guess would be number 3.

JLS: Each string literal is a reference (�4.3) to an instance (�4.3.1, �12.5) of class String (�4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (�15.28)-are "interned" so as to share unique instances, using the method String.intern.
 
Sahul Yasin
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Jim,
where did you get this kind of question.When i saw this question , suddenly i thought 2 , but actually 3. Very good tempting question.
 
Jim Crawford
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mohamed Yasin:
hi Jim,
where did you get this kind of question.When i saw this question , suddenly i thought 2 , but actually 3. Very good tempting question.

It wasn't my question, I just attempted to answer it.
 
Harvinder Singh
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I found this question on the CD that comes with the java certification book by Simons.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic