Computer Science Canada

Swap

Author:  dchini [ Sun Oct 26, 2008 8:18 pm ]
Post subject:  Swap

I am puzzled with this code....

code:
class Funcs
{
public static void swap(Object a, Object b)
{
                Object temp = a;
                a = b;
               b = temp;
        }
   
public static void main(String[] args)
{
                String x= "hello";
                String y = "goodbye";
                System.out.println(x);
                System.out.println(y);
                swap(x,y);
                System.out.println(x);
                System.out.println(y);
        }   
}


It prints

hello
goodbye
hello
goodbye



I thought it should have printed

hello
goodbye
goodbye
hello

Author:  OneOffDriveByPoster [ Sun Oct 26, 2008 8:45 pm ]
Post subject:  Re: Swap

Java passes references by value. If you change what your function parameters refer to in a function, the change does not get reflected in the caller.

Author:  A.J [ Sun Oct 26, 2008 10:03 pm ]
Post subject:  Re: Swap

I think what u shud do is do the swapping in the main body instead of creating a separate function to do it for u.

Author:  Saad [ Sun Oct 26, 2008 10:07 pm ]
Post subject:  Re: Swap

A.J @ Sun Oct 26, 2008 10:03 pm wrote:
I think what u shud do is do the swapping in the main body instead of creating a separate function to do it for u.


But what happens in the case you want to swap a lot of things? Clearly you don't want to be copy/pasting the same code if you can make it a function.

Author:  rdrake [ Sun Oct 26, 2008 11:26 pm ]
Post subject:  RE:Swap

Aren't strings in Java immutable?

Author:  OneOffDriveByPoster [ Mon Oct 27, 2008 8:35 am ]
Post subject:  Re: Swap

Saad @ Sun Oct 26, 2008 10:07 pm wrote:
A.J @ Sun Oct 26, 2008 10:03 pm wrote:
I think what u shud do is do the swapping in the main body instead of creating a separate function to do it for u.
But what happens in the case you want to swap a lot of things? Clearly you don't want to be copy/pasting the same code if you can make it a function.
For the sake of the OP:
If you are swapping a lot, you are more than likely to be swapping array elements or elements in a container. That is entirely possible to do in a helper function.
Hint: pass the array/container in with the indices/keys.


: