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

real confusing stuff

 
srijan sharma
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all ranchers,
just have a look at the code
though it has been discussed before i could not get it..
the output is 10,0,20
but i feel it should be 10,0,10
as once refernce is being lost how it can have the old value
pl. guide
thanks in advance
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;
//System.out.println("Before another = "+ v.i);
another(v,i);
System.out.println("After another = "+ v.i);
}//End of amethod
public void another(ValHold v,int i){
i=0;
v.i = 20;
ValHold vh=new ValHold();
System.out.println("vh.i ="+vh.i);
v=vh;
System.out.println(v.i+" "+i);
}//End of another
}

regards
srijan
 
Philosopher
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great question. You need to understand that Java passes arguments by value. A copy of the argument is created and passed to the method. In this code, when another(v,i) is called, compiler internally creates a reference variable which is also pointing to the same object. Here this variable is also named v(This v is in the argument list of another, you can name it anything). Using this v you change the object in the memory to hold the i value equal 20 which was previously 20. Now you make this reference variable point to another memeory object vh which has value 10. When the method returns to the caller, the previous v comes to scope. IT IS NOT THE SAME V IN THE ANOTHER METHOD THAT WAS A COPY OF IT. This v is still pointing to the memory object which has value of i equal 20 thats why it prints 20.
If its not clear still, I will suggest you practice it graphically with a pen and paper with the steps above mentioned. Let me know if you need any further help.
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi srijan,
This article http://www-106.ibm.com/developerworks/library/praxis/pr1.html?dwzone=java has a decent example of the difference between passing variables as values vs reference.
I'm going to move this post to the Certification Study forum as it's not related to results.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic