public static void main(String[] args) {
Foo[] foo1 = new Foo[1];
Foo[] foo2 = new Foo[1];
foo1[0] = new Foo();
foo2[0] = new Foo();
foo1[0].x = 1;
foo2[0].x = 2;
swapA(foo1, foo2);
System.out.println("Swap A " + foo1[0].x + " " + foo2[0].x);
swapB(foo1[0], foo2[0]);
System.out.println("Swap B " + foo1[0].x + " " + foo2[0].x);
swapC(foo1[0], foo2[0]);
System.out.println("Swap C " + foo1[0].x + " " + foo2[0].x);
swapD(foo1, foo2);
System.out.println("Swap D " + foo1[0].x + " " + foo2[0].x);
}
public static void swapA(Foo[] o1, Foo[] o2) {
Foo[] temp;
temp = o1;
o1 = o2;
o2 = temp;
System.out.println("Swap A " + o1[0].x + " " + o2[0].x);
}
public static void swapD(Foo[] o1, Foo[] o2) {
Foo temp;
temp = o1[0];
o1[0] = o2[0];
o2[0] = temp;
System.out.println("Swap D " + o1[0].x + " " + o2[0].x);
}
public static void swapB(Foo o1, Foo o2) {
Foo temp;
temp = o1;
o1 = o2;
o2 = temp;
System.out.println("Swap B " + o1.x + " " + o2.x);
}
public static void swapC(Foo o1, Foo o2) {
int temp;
temp = o1.x;
o1.x = o2.x;
o2.x = temp;
System.out.println("Swap C " + o1.x + " " + o2.x);
}
Swap A 2 1
Swap A 1 2
Swap B 2 1
Swap B 1 2
Swap C 2 1
Swap C 2 1
Swap D 1 2
Swap D 1 2
Just to want have a better understanding, why swapA and swapB doesn't change the value when print in the main method, but by itself method it change the value. I thought that object and array was pass by reference when you swap it the original value will change as well?