Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pass value

 
luk Hann
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I still had hard time to understand why s1 was changed while s2 not. Please help me on this because I really don't want to "guess" an answer in the real exam when I face this kind of questions. Thanks. Luk.
import java.util.*;
> public class TestClass
> {
> public static void doStuff(Stack x1, Stack x2)
> {
> x1.push(new Integer(100));
> x2=x1;
> }
>
> public static void main(String args[])
> {
> Stack s1 = new Stack();
> Stack s2 = new Stack();
>
> doStuff(s1, s2);
> System.out.println(""+s1 +" "+ s2);
> }
> }
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Someone explained it once to me this way (I think it was maha anna or Tony Alicea).
When you reference a variable to an object it is like a sign pointing to a city. So let's say s1 points to one city and s2 points to another city. You pass these values into a method, now you have s1 and (inside the method) x1 pointing to the same city and s2 and x2 pointing to the same city. Then you said I want to do something to the city x1 is pointing at, you do this by saying:
x1.push(new Integer(100));
But s1 and x1 are still pointing there so both of them see the change. You changed the city, not the pointer. Now the next statement says I want x2 to now point at the same place x1 is pointing to. You do this by saying:
x2 = x1;
However, you didn't change the sign s2, you only changed the sign x2. So s2 doesn't change. In the end you have 3 signs pointing to the same city, x1, x2, and s1 and then s2 pointing to one city. Of course when you leave the method x1 and x2 go out of scope.
Does that make sense?
Bill
 
John Bateman
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I added a few more print statements and some comments to your code illustrate that all parameters are passed by value. You just have to remember that in the case of primitives you get an actualy COPY of the promitiev, but in the case of objects you get a COPY of the REFERENCE, not the object itself.

 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Luk,
Also check this article http://www-106.ibm.com/developerworks/library/praxis/pr1.html?dwzone=java which explains the way Java passes values to methods.
Hope it helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic