File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Pass value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Pass value" Watch "Pass value" New topic

Pass value

luk Hann
Ranch Hand

Joined: Jan 29, 2001
Posts: 48
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

Joined: Jun 30, 2000
Posts: 1070
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?
John Bateman
Ranch Hand

Joined: Mar 09, 2000
Posts: 320
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.

SOURCE CODE should be SURROUNDED by "code" tags.
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Also check this article which explains the way Java passes values to methods.
Hope it helps.
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform

Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
I agree. Here's the link:
subject: Pass value
It's not a secret anymore!