What happens when you change a reference inside a method? (7)

What happens when you change a reference inside a method?

public void reverseX(int[] nums) {
    int[] nums2 = new int[nums.length] ;
    for( int i=0 ; i < nums.length ; i++ )
        nums2[i] = nums[nums.length-(i+1)] ;
    nums = nums2 ;
};

This compiles fine.

Code is from here, and shown as an example of what not to do.

http://www.cs.nyu.edu/~cconway/teaching/cs1007/notes/arrays.pdf

Jon Skeet
people
quotationmark

Objects, reference types are suppose to be immutable.

Not all of them. Some, but not all. For example, String is immutable, but StringBuilder isn't. All arrays are mutable.

What happens here when nums is set to nums2.

The nums variable is given a new value, which is equal to the existing value of nums2.

That doesn't change the state of the objects that those variables refer to at all. It just changes the variable value itself.

Imagine the variables are pieces of paper. The integer array is like a house, and the values of the variables are like addresses written on the pieces of paper. This line:

nums = nums2 ;

... is just like copying what's written on one piece of paper onto another. That doesn't change the contents of the house that the address happens to refer to, right?

Now nums is just a local variable - because it's a parameter. That doesn't change anything in the calling code at all, because arguments are always passed by value in Java. So you're setting a local variable value just before the end of the method, and that's all. It will have no meaningful effect.

If none of this helps you, you'll need to ask a more specific question.


1 Note that I'm not saying that a reference is necessarily a memory address - the word "address" is just convenient in the analogy.

people

See more on this question at Stackoverflow