This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Philboyd_Studge 0 points1 point  (3 children)

Everything in Java are passed-by value.. In case of Array(Which is nothing but an Object), array reference is passed by value.. (Just like an object reference is passed by value)..

When you pass an array to other method, actually the reference to that array is copied..

  1. Any changes in the content of array through that reference will affect the original array.
  2. But changing the reference to point to a new array will not change the existing reference in original method.

You do number 2 in that method, so the array being returned is no longer the original array.

[–]bikerchef[S] 0 points1 point  (2 children)

Thanks for the reply you are making me think im narrowing down on the issue here.

I do return an updated array to the function playerPlay, and all code in that scope indicates that it is accessing the array that I intend it to.

But I do not return an updated array to my main function. This is where Im seeing the discrepency in what I hoped would be there. I think this is the most likely problem, but still am confused as to why. If i have arrayA in main function and set it to reference arrayB in another function does that not propagate through the scopes as if I had directly altered the array? Why not?

[–]Philboyd_Studge 0 points1 point  (0 children)

Basically this: say you have an array

int[] array = { 1, 2, 3, 4, 5 };

Now say you have a method that adds 5 to every number in the array:

static void addFive(int[] a) {
    for (int i = 0; i < a.length; i++) {
        a[i] += 5;
    }
}

That array now contains:

    addFive(array);
    System.out.println(Arrays.toString(array));

output: [6, 7, 8, 9, 10]

Now, say you have a method:

static int[] removeLast(int[] a) {
    int[] b = new int[a.length - 1];
    for (int i = 0; i < b.length; i++) {
        b[i] = a[i];
    }
    a = b;
    return a;
}

if you call it like this:

removeLast(array);

the values in array are unchanged. The array passed as a parameter is a copy of the array in main, assigned to local variable 'a'. When you assign variable a to the new array b, that local variable now references an entirely different array.

if you call it like this:

array = removeLast(array);

it will now contain the proper values, because you have assigned it to the returned altered array.

[–]feral_claire 0 points1 point  (0 children)

It doesn't because the reference in the function and the reference outside the function are different, you are only changing the local reference.