Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number of objects created

 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question from Valiveru's exam.
How many String objects are created when we run the following code.
String s1,s2,s3,s4;
s1 = "Hello"; //line 1
s2 = s1; //line 2
s3 = s2 + "Pal";//line 3
s4 = s3; //line 4
A.1
B.2
C.3
D.4
E.We can't say.
The ans given is c (ie 3 objects) . My answer was b(2 objects)

I would say that at line 1 and 3 objects are created. At line 2, s2 points to an already cretaed object and at line 4 s4 points to an already cretaed object line 3. Am I right?
 
Mohit Goyal
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well the answer given is rite.
3 objects r created.
on line 1 one object is created
on line 2 the reference to that object is assigned to s2
on line 3 an object with the value "Pal" is created which has no reference. then the strings r concatenated and a 3rd string object "HelloPal" is created
on the 4th line the reference to this new object is assigned to s4
[ December 07, 2003: Message edited by: Mohit Goyal ]
[ December 07, 2003: Message edited by: Mohit Goyal ]
 
mrudul joshi
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

According to me, only 2 objects are created in the above program.I called the method hashCode()from object class on every string object created.The output would have been three different hashcodes for each created object it there had been 3 objects created.
But, if you see the output,you will see just the two objects i.e.only two hashcodes.
(I am sorry something went wrong in the cut and paste)
Please see the output for ypurself, just to crosscheck!

69609650
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lakshmi,
The answer given is correct, 3 objects are created:
1) "Hello" //line 1
2) "Pal" // line 3
3) The result of concat. "Hello" and "Pal" // line 3
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic