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;
}
}