I know this works:
public static void main(String[] args) {
String[] arr = {"aaa","bbb"};
int i = 0, j = 1;
System.out.println("Before swap "
+ "arr[0] = " + arr[i]
+ " arr[1] = " + arr[j]);
swap(arr, i, j);
System.out.println("After swap "
+ "arr[0] = " + arr[i]
+ " arr[1] = " + arr[j]);
}
static void swap(String[] arr, int i, int j){
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
But I don't understand why, they are both void.
If I go to the trouble of creating a class object with instance
variables, and a method swapString, would it have worked?
On Sep 5, 8:00 pm, miga <[EMAIL PROTECTED]> wrote:
> 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>- Hide quoted text -
>
> - Show quoted text -
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---