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

Mock test question

 
mahesh deshpande
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question was debated somewhere else in a thread at http://www.jchq.net/discus/messages/1/20385.html?#POST1594
Marcus
 
Marcus Green
arch rival
Rancher
Posts: 2813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And also at http://www.jchq.net/discus/messages/1/20112.html?
 
mahesh deshpande
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Peter and Marcus green.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic