aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mock test question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock test question" Watch "Mock test question" New topic
Author

Mock test question

mahesh deshpande
Greenhorn

Joined: Oct 26, 2000
Posts: 19
Can anybody explain in detail why and how the output of the following code is 10,0,20
class valHold {
public int i = 10;
}
public class obParm{
public static void main ( String arg[]){
obParm o = new obParm();
o.amethod();
}
public void amethod ()
{
int i = 99;
valHold v = new valHold();
v.i = 30;
another( v,i);
System.out.println(v.i);
}
public void another ( valHold v, int i)
{
i =0;
v.i = 20;
valHold vh = new valhold();
v = vh
System.out.println( v.i + " " + i );
}
)
peter waterhouse
Greenhorn

Joined: Oct 20, 2000
Posts: 15
toughie this...
follow it through...
when it hits amethod v.i = 30 and local i = 99, it then calls another.. passing v by reference
you have an object now with i=30 and references to it as follows:
amethod's v,
anothers v.
these two references are distinct, yet point to the same object, that is important.
The first statement in another sets the local i to 0.
The second thing in another is to change the objects value to 20. so now both amethods v. and anothers v. are reffering to an object with i=20.
you then create a new object with the default value i=10. vh references this object.
you then assign the anothers v. reference to the new object instead of the old object. HOWEVER. amethods v. reference remains pointed at the same (old) object.
hence by the system.out in another v references an object with i=10 and the local i is 0. therefore 10,0 is printed.
you then return to the amethod method. here the v is still referring the object where i=20, therefore when called by system.out. 20 is printed.
hence 10,0,20.
if you have trouble with following the references try drawing diagrams, thats how I normally figure out this sort of problem!
tarra.
Pete
Marcus Green
arch rival
Rancher

Joined: Sep 14, 1999
Posts: 2813
This question was debated somewhere else in a thread at http://www.jchq.net/discus/messages/1/20385.html?#POST1594
Marcus


SCWCD: Online Course, 50,000+ words and 200+ questions
http://www.examulator.com/moodle/course/view.php?id=5&topic=all
Marcus Green
arch rival
Rancher

Joined: Sep 14, 1999
Posts: 2813
And also at http://www.jchq.net/discus/messages/1/20112.html?
mahesh deshpande
Greenhorn

Joined: Oct 26, 2000
Posts: 19
Thank you Peter and Marcus green.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Mock test question