This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Mock Exam Errata and the fly likes Marcus Green mockexam #2 Q51 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "Marcus Green mockexam #2 Q51" Watch "Marcus Green mockexam #2 Q51" New topic
Author

Marcus Green mockexam #2 Q51

xiaofeng wang
Greenhorn

Joined: Jul 25, 2001
Posts: 1
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

Joined: May 30, 2001
Posts: 24
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

Joined: May 25, 2001
Posts: 1
I see, many thanks.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Marcus Green mockexam #2 Q51