• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Marcus Green mockexam #2 Q51

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I see, many thanks.
 
I love a woman who dresses in stainless steel ... and carries tiny ads:
New web page for Paul's Rocket Mass Heaters movies
https://coderanch.com/t/785239/web-page-Paul-Rocket-Mass
reply
    Bookmark Topic Watch Topic
  • New Topic