1
package main;

public class Main {
    double radius;
    public Main(double newRadius) {
        radius = newRadius;
    }


    public static void main (String [] args) {
        Main x = new Main(1);
        Main y = new Main(2);
        Main temp;
        // try to swap first time
        temp = x;
        x = y;
        y = temp;
        System.out.println(x.radius + " " +  y.radius);
        x = new Main(1);
        y = new Main(2);
       // try to swap second time
        swap(x, y);
       System.out.println(x.radius + " " + y.radius);
    }
    public static void swap(Main x, Main y) {
        Main temp = x;
        x = y;
        y = temp;
    }

}

Why the first time worked, but the second time didn't? The first one did the swap, but the second one didn't. I'm passing the reference to the function. Why this doesn't work?

Roy Derek
  • 31
  • 1
  • 5
    References are passed by value. The variables inside the method are not the variables outside the method, so reassigning them doesn't alter external variables. See [Is Java pass-by-reference or pass-by-value?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – khelwood Nov 10 '18 at 13:11

1 Answers1

0

Your mistaking how references are passed, your making a scope where references are swapped and then that scope ends.

Try storing the value of the field in the variable e.g. temp = x.radius and then assign to y.radius.

The reason why it works the first time is that the scope is the same.

Jay
  • 3,276
  • 1
  • 28
  • 38