This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Number of objects created Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Number of objects created" Watch "Number of objects created" New topic
Author

Number of objects created

Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
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?


Thanks,<br />Lakshmi.
Mohit Goyal
Ranch Hand

Joined: Nov 09, 2003
Posts: 65
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

Joined: Nov 12, 2003
Posts: 54

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

Joined: Jul 21, 2003
Posts: 522
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


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. <br />- What truth? <br />- That there is no spoon!!!
Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
Thank you all...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Number of objects created
 
Similar Threads
Strings Again.......
String objects creation
string question
HOW MANY OBJECTS ARE CREATED
Mock Exam Q