
-----------------------------------
dchini
Sun Oct 26, 2008 8:18 pm

Swap
-----------------------------------
I am puzzled with this 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

-----------------------------------
OneOffDriveByPoster
Sun Oct 26, 2008 8:45 pm

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.

-----------------------------------
A.J
Sun Oct 26, 2008 10:03 pm

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.

-----------------------------------
Saad
Sun Oct 26, 2008 10:07 pm

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.

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.

-----------------------------------
rdrake
Sun Oct 26, 2008 11:26 pm

RE:Swap
-----------------------------------
Aren't strings in Java immutable?

-----------------------------------
OneOffDriveByPoster
Mon Oct 27, 2008 8:35 am

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.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.
