0
public static void mystery(int[] arr) {
    int[] tmp = new int[arr.length];
    tmp[0] = arr[arr.length-1];
    tmp[arr.length-1] = arr[0];
    arr = tmp;
}

int[] a = {2,3,4};
mystery(a);

When I run this, I get that even after calling mystery(a), the value of a is still

a = {2,3,4};

Java arrays are mutable, and all arguments are pass by reference. Since in the method arr points to the memory stored in tmp after the method, why is a unchanged?

cgnorthcutt
  • 3,890
  • 34
  • 41
  • You can alter one or all of the indexes in the array inside your function, but that form of assignment does not work. – mttdbrd Apr 24 '14 at 21:01
  • If we consider StackOverflow as a guide for programming in language, I think this question/answer is beneficial apart from the http://stackoverflow.com/questions/40480/is-java-pass-by-reference page. – cgnorthcutt Apr 24 '14 at 21:07

1 Answers1

4

In java changing the argument of a method to refer to some other object does not have any effect on the original argument. Therefor a does not point to tmp after the execution of mystery.

To accomplish the swapping your mystery method needs to work on arr directly

geoand
  • 60,071
  • 24
  • 172
  • 190
  • Thank you! I did not know that it made a copy of the reference variable. I thought the reference variable was reference as well. Perfect. – cgnorthcutt Apr 24 '14 at 21:07