I'm honestly not sure; I tried this, and it seemed to swap them properly during Swap2, but after Swap2, the values for x.a and y.a seem to revert to their original state:
public static void swap2(test x,test y){
System.out.println("swap2");
test temp=x;
System.out.println("temp=x");
System.out.println("temp = "+temp.a+", x = "+x.a+", y = "+y.a);
x=y;
System.out.println("x=y");
System.out.println("temp = "+temp.a+", x = "+x.a+", y = "+y.a);
y=temp;
System.out.println("y=temp");
System.out.println("temp = "+temp.a+", x = "+x.a+", y = "+y.a);
}
here's my output:
swap2
temp=x
temp = 2, x = 2, y = 5
x=y
temp = 2, x = 5, y = 5
y=temp
temp = 2, x = 5, y = 2
2 5 //this is the end result from System.out.println(x.a+" "+y.a);
...so yeah, they do swap correctly inside the method. I'm not sure why, but I'd hazard a guess...
My first thought was that if you pass a instance of a class to a method as an argument (In this case, x and y are passed to Swap2 expecting two objects of type 'test'), then you reassign the object, you're reassigning it only to the local instances of x and y, and local variables and instances are lost when a method closes... basically, when you do the '=' operator on an instance of a class, you're making a 'copy' of the original class that contains the pointers to the memory location of the original data.
The reason the first one works is because you're explicitly editing the original integer (because swap1's test x refers to Main's test x, which points to the memory location of integer x.a), but in swap2, you're making a copy of test y into test x (when you do x = y; so test y will still refer to test y from Main, but test x in swap 2 now refers to test y in main as well, while 'temp' holds the references to test x and the pointers to the memory location where its integer is stored).
So, basically, when you run swap 2, you're copying test x and test y over to the arguments of swap2, then you swich what the local variables in swap 2 point to, which does not change the original data, nor does it change what the original test c and test y point to in Main.
...I think.
If someone else comes along and either corrects me, or explains this better, that would be cool ^^
I'll ask a lot of questions (most of them probably stupid stuff). Bear with me, i'm still learning! ^_^ Also, I'll try to answer as many questions as I can as well, but I'm not very good yet. I'm sure I'll be of more use once I get better :)