Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcusgreen Mock Exam1 Question 51

 
Santoo
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please explain the code
answer for this is 10,0,20
Question 51 from Marcusgreen mock exam1
Given the following code what will be the output?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
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);
}//End of amethod
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);
}//End of another
}
Thanks in advance.
 
Biju Narayanan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let us start with amethod() call. Inside amethod(), object v is created and its 'i' has a value 10. now i changes to 30.
now the another() method is up. this method copies the object reference from v of amethod() to v of another(). See at this point of time, two vs are in the memory. Both points to the same object. so changing i inside another() reflects in amethod() also. v.i changes to 20. now another obect is created and assigned to v. so v.i is 10. This is why 10 is printed first.
The other single i is just a local variable of another() and has been initialized to 0. so this prints the 0 next to 10. now
having done with another(), execution goes back to amehod().
remember that v.i has already changed to 20.
The print statement will print the last number which is 20.
Hope this helps
Biju
 
Santoo
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Biju Narayanan:
Let us start with amethod() call. Inside amethod(), object v is created and its 'i' has a value 10. now i changes to 30.
now the another() method is up. this method copies the object reference from v of amethod() to v of another(). See at this point of time, two vs are in the memory. Both points to the same object. so changing i inside another() reflects in amethod() also. v.i changes to 20. now another obect is created and assigned to v. so v.i is 10. This is why 10 is printed first.
The other single i is just a local variable of another() and has been initialized to 0. so this prints the 0 next to 10. now
having done with another(), execution goes back to amehod().
remember that v.i has already changed to 20.
The print statement will print the last number which is 20.
Hope this helps
Biju

Thanks Biju,I got the answer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic