Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter passing in Java

I know that Java is always pass-by-value, but I do not understand why this works:

public static void swap(int[] arr, int i, int j)
{
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static void main(String[] args)
{
    int[] arr = {3, 4, 5, 6};
    swap(arr, 1, 3);
    // arr becomes {3, 6, 5, 4}
}

And this does not work:

public static void swap(int[] arr, int[] arr2)
{
    int[] tmp = arr;
    arr = arr2;
    arr2 = tmp;
}
public static void main(String[] args)
{
   int[] arr = {3, 4, 5, 6};
   int[] arr2 = {1, 2, 5, 6};
   swap(arr, arr2);
}

Why?

like image 349
SorcerOK Avatar asked Jul 04 '14 08:07

SorcerOK


1 Answers

In the second method, you are trying to swap references, which will not work because the references themselves are pass-by-value.

The first method works correctly because it changes the object referenced by the array (which is mutable), it does not change the reference itself.

Check out this blog post for more details on the differences between pass-by-value and pass-by-reference.

like image 187
geoand Avatar answered Nov 15 '22 17:11

geoand