On Sep 5, 11:14 am, Norman Ho <[EMAIL PROTECTED]> wrote:
> Hi,
> I am just doing some recap on what I have study so far, and I try this
> codes to swap two strings, and it doesn't work. As I learnt, "String"
> type is not a primitive type, so when being passed to a method, it
> should be passed by reference, but when it comes back from the swap
> method, the strings are still the same. How can I make the swap to
> work?
>
> public static void main(String[] args) {
>
> String a = "aaa", b = "bbb";
> System.out.println("Before swap "
> + "a = " + a
> + " b = " + b);
> swap(a, b);
> System.out.println("After swap "
> + "a = " + a
> + " b = " + b);
> }
The problem is that the variables are local the functions, so that
their changes are not seen outside the function.
I think the solution would be to pass an array of those strings, swap
them, just similar as you did, then return the new array, so no void.
Then you will put the returned array in another empty new one in the
main method, and you retrieve the x and y strings.
Or you swap directly in the main (question of scope of the
references).
> static void swap(String x, String y){
> String temp = x;
> x = y;
> y = temp;
> }
>
> norman.
See also this thread: <http://forums.sun.com/thread.jspa?
threadID=638652&messageID=3739675>
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---