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

urgent pls explain

 
ravi ckumar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
}
why is the o/p 10,0,20 pls explain the last 20 , why should it be 20 i feel the answer is 30 or 10
pls explain
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without giving the answer right away, remember these rules.
1. When you pass primitives to a method, you are passing a copy of the primitive. What that means is that when you have a privitive with the value 10 and you pass it to a method that changes the primitive to 20, it doesn't effect the original value 10, it only changes the argument in the method.
2. When you pass an object to a method, again you are passing a copy of the refernece to the object. But here, if the object you passed has a memeber variable set to 10, and you change the memeber variable in the method then the original object is also changed. This can be a little confusing at first.
So try the method again and see what you get. The answer is correct.
Bill
 
ravi ckumar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank u,
that was helpful, i will just try to explain the answer just to see if i got it right or not,
the answer 10, 0 20
first 10 & 0 are becuse of the local variables , since we are operating on the copy of the object the line v = vh has no effect on the original reference so the s.o.println method here prints 10 , 0
the next 20 is because we are operating on the variable of the reference since it is a member variable the original one will get effected. so we get the o/p as 20
hope i got it right !! thanks
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice job ravi. You are correct. These questions can be difficult, best thing is to get a pen and paper and follow the code for the output.
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic