This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
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

Marcus Green mockexam #2 Q51

 
xiaofeng wang
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question 51)
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
}
1) 10,0, 30
2) 20,0,30
3) 20,99,30
4) 10,0,20
Marcus' answer is 4) 10,0,20. I think the answer should be 20,0,20. How about this matter.
 
Bill Tripper
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer given by Marcus is correct. In the "another" method, the line:
ValHold vh = new ValHold();
creates a new object of type ValHold, such that vh.i == 10;
The next line
v = vh;
makes the reference "v" point to that same new ValHold object already pointed to by v whose member variable is set to 10. At this point v is a reference to a different object from the one it referred to two lines previous.
After that statement is executed, the "v" in method "another" refers to a ValHold object with v.i == 10. The "v" in method "amethod" refers to a different ValHold object with v.i == 20. Hence the println method inside method "another" prints a value of 10 (followed by zero) while the println method inside method "amethod" prints a value of 20.
 
Max Wang
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see, many thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic