0

In the following code, I want to swap two objects but the first method (swap1) which swap the object reference variables of the two objects doesn't work while the other method (swap2) which swaps the values of the objects' data fields x.radius & y.radius work properly so what's the problem with the first method? why when I swapped the two reference variables of the two objects, they didn't refer to each other?

public class Main {
    public static void main(String [] args) {
        TestCircle circle1 = new TestCircle(1);
        TestCircle circle2 = new TestCircle(2);
        swap2(circle1,circle2);
        System.out.println("After swap2: circle1 = " +
        circle1.radius + " circle2 = " + circle2.radius);

    }

    // false swap
    public static void swap1(TestCircle x, TestCircle y){
        TestCircle temp = x;
        x = y;
        y = temp;
    }

    // real swap
    public static void swap2(TestCircle x, TestCircle y){
        double temp = x.radius;
        x.radius = y.radius;
        y.radius = temp;
    }

}

class TestCircle {
    double radius;

    TestCircle(double newRadius){
    radius = newRadius;
    }
}
  • Note, neither one is a true swap. Java doesn't allow such a thing. (If it did, the "false swap" would be the true one.) The closest you'll get in Java is swapping values of fields. – cHao Feb 08 '18 at 21:10
  • Because Java is always pass-by-value, `swap1` is swapping the values of its parameters, *not* the values of the local variables in `main`. – Andy Turner Feb 08 '18 at 21:12
  • @cHao you can swap local variables: you just have to do it in the same method. – Andy Turner Feb 08 '18 at 21:12
  • @AndyTurner: If you do it in the same method, though, then you defeat the purpose of the example. :) – cHao Feb 08 '18 at 21:14
  • I know that the second swap isn't true either but I know that java allows pass-by-sharing for both objects and arrays & I thought that I can swap the two objects by swapping their reference variables so what is wrong with the method, really I can't figure out what is wrong?? – Mostafa Fayed Feb 08 '18 at 21:17
  • yes yes yes, I found it !! when I used the second method I just swapped the input values of the reference variables but I didn't access the objects them selves so the reflection isn't reflected on the objects but in the second method I assigned new values to the data fields of the objects by using the swap but it's not a swap itself. thanks a lot guys :) – Mostafa Fayed Feb 08 '18 at 21:22

0 Answers0