0

Here is the code of the class i have written

class Demo
{
    int x,y;
    Demo(int a,int b){x=a;y=b;}
    public void swap(Demo ref) // interchanges field values of x and y
    {
        int temp;
        temp=ref.x;
        ref.x=ref.y;
        ref.y=temp;
    }

    public void change(Demo ref1,Demo ref2) // supposed to interchange to class variables of Demo class
    {
        Demo temp = ref1;
        ref1 = ref2;
        ref2 = temp;
    }
}  

swap method works fine i.e. interchange values of x and y.

Now, I have two questions here:

  1. how the swap method is able to change the actual data passed to it? (I have read that their is no pass by reference in Java.)
  2. why change method does not interchange class references?
Shashi
  • 746
  • 10
  • 39
  • 1
    The answer: http://stackoverflow.com/questions/40480/is-java-pass-by-reference – Genzer Sep 14 '13 at 16:54
  • x and y are primitive, while ref is an Object. when objects are passed as argument you will pass the reference. And for primitive a copy of the value is passed – upog Sep 14 '13 at 17:00

1 Answers1

3
  1. Pass-by-value in Java is somewhat interesting. You're passing a reference to an object on the heap by value. So, by dereferencing/accessing ref you're accessing an existing object on the heap. That object's fields are changed, and any other references to that Demo instance will reflect these changed when dereferenced(as it's the same object).

  2. Because references are passed by value, calling change(myDemo1, myDemo2) passes the values of the myDemo1 and myDemo2 references. We're not passing in a reference to the myDemo1 reference. Switching around the values won't affect them outside the method.

Let's just say that for simplification's sake the references are valued 12345 and 23456. For the first, we pass in a reference to 12345, and we then change things with that object. Any other dereferencing of 12345 will reflect those changes.

Now, let's try the following:

public static void main(String... args){
    Demo d1,d2;
    d1=new Demo(1,2); //VALUE of d1 is 12345, and deferencing d1 will get us a demo object at 12345 with 1 and 2.
    d2=new Demo(9,8); //VALUE of d2 is 23456. Deference it, get a demo with 9 and 8.
    change(d1,d2); //d1 and d2 are passed by VALUE. `change()` gets its own copy of d1 and d2 to play with.
}
nanofarad
  • 40,330
  • 4
  • 86
  • 117