Parameter passing in Java

java, pass-by-value

Solution

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.

Problem

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?

Original source

Related problems