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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With