• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

about Object references as method parameters

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
this question is from:http://www.jchq.net/tutorial/05_04Tut.htm
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
}
what's output:
1)10,0,30
2)20,0,30
3)20,99,30
4)10,0,20
output is 10,0
20
my question is: b/c another method passed the field of the object, and v=vh, so the output is 10 (b/c v.i=10 from class ValHold), and i=0 (b/c another method i=0) mmm.. but, why in amethod "System.out.println(v.i);" print out v.i=20?
b/c another method's v.i=20? or say vh.i=20?...???..
please explain why, why, why... ^__^*
thanks a lot.
martha
p.s. ohh.. ans. 4) and good day.
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.out.println(v.i) prints 20. Here is the explanation:
Object reference is being passed to another(ValHold v, int i)
v still points to the same object and changes v.i to 20
The reference is lost when v=vh is executed. When control returns to the calling method, it prints 20, as a result of the above change.
 
Martha Yeh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
mm.. i cc.. thanks a lot ^__^*
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic