hi
I want to swap two object through a method. I tried to do something as given below(I have written down a simplfied code here):
<code>
class myclass{
int x;
int y;
String s;
myclass(int x,int y,String s)
{
this.x=x;this.y=y;this.s=s;
}
}
public class test{
public static void main(string []args)
{
myclass obj1=new myclass(1,2,"first");
myclass obj2=new myclass(3,4,"Second");
system.out.println(obj2.s);
system.out.println(obj1.s);
swap(obj1,obj2);
system.out.println(obj1.s);
system.out.println(obj2.s);
}
void swap(myclass o1,myclass o20
{
myclass temp=o1;
o1=o2;
o2=temp;
}
}
</code>
But ofcourse, the objects are not swapped in when we return to main method from swap.This was confusing because we learnt that in
java objects are passed by reference. after thinking for sometime, I have come to a conclusion. I dunno if it is the right answer, but this is what I think:
In java, value held by the object reference (i.e. the address of the object it points to) is actually passed , which is accepted by a another object reference.
In the swap method we get a object refrence o1 which points to the same object pointed(referenced) by obj1. Similarly o2 point to object pointed by obj2.When we swap, we are actually pointing o1 to object pointed by o2(obj2), and pointing o2 to object pointed by o1(obj1).But obj1 and obj2 continue top point to what they pointed before calling swap.
Is what I think correct?
So how do I swap two object through a method and get it swapped when I return from that method.
regards
Tanveer