0

The output to below main is [5,4,3,2,1] [1,2,3,4,5]

Which makes no sense to me. yes, the first time I ran "reverseArrayIteratively", I'm definitely expecting [5,4,3,2,1] so that's the correct output, but after the second function (reverseArrayRecursively), I was expecting it to also return [5,4,3,2,1] because Java is supposed to be "pass by value", so I didn't expect "reverseArrayIteratively" to actually change around the values of myIntArray. I thought that myIntArray inside the main will stay [1,2,3,4,5] no matter how many times I call reverseArrayIteratively or reverseArrayRecursively. What's going on here?

public static void main(String[] args) {
        // TODO Auto-generated method stub  
        int[] myIntArray = {1,2,3,4,5};
        System.out.println(Arrays.toString(reverseArrayIteratively(myIntArray, 0, myIntArray.length-1)));
        System.out.println(Arrays.toString(reverseArrayRecursively(myIntArray, 0, myIntArray.length-1)));
    }

    public static int[] reverseArrayIteratively(int[] array, int first, int end) {
        while (first < end) {
            int temp = array[end];
            array[end] = array[first];
            array[first] = temp;
            first++;
            end--;
        }
        return array;   
    }   

    public static int[] reverseArrayRecursively(int[] array, int first, int end) {
        int temp = array[end];
        array[end] = array[first];
        array[first] = temp;
        first++;
        end--;
        if (first < end) {
            reverseArrayRecursively(array, first, end);
        }
        else {
            return array;
        }
        return array;
    }
Terry Bu
  • 889
  • 1
  • 14
  • 31

1 Answers1

4

It is behaving as pass-by-value. Your confusion, I think, stems from what that means for non-primitive parameters (and an array is an object, not a primitive). For object parameters, what's passed by value is always the reference to the object. In your recursive method, you are modifying the elements of the array parameter, so of course it is changing the array elements back in the calling code.

If you're from a C++ background, think of Java references as C++ pointers, not as C++ references.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • I like to call it pass-reference-by-value – zinking Jan 08 '15 at 02:09
  • If he created a new array and returned that, his original would stay the same right? – D. Ben Knoble Jan 08 '15 at 02:25
  • @BenKnoble - Yes, the original would stay the same. But the new array would not be what was expected because each recursive call would create a new array, so all recursion past the initial call would not affect the returned array the way it should. – Ted Hopp Jan 08 '15 at 03:45