funKatz
funKatz

Reputation: 33

Using an array as the parameter for a method in Java

I recently started coding in Java. Previously I used C++ as my most used language.

I have been using some methods (functions in C++) to solve some algorithm questions. However, I have found some unexpected things happening depending on the type of parameters I used.

When I use an int type variable as a parameter, the method does exactly what I expect.

enter image description here

The value of variable b is never changed; the method's result is only applied to variable c.

enter image description here

Now here is the problem. When I use an int type "array" as a parameter, this is what happens.

'''class Main {

static int[] add_three(int[] input) {
    int[] result = input;
    result[3] += 3;
    return result;
}

public static void main(String[] args) {
    int[] b = {1, 2, 3, 4};
    for (int i = 0; i < 4; i++) System.out.print(b[i] + " ");
    System.out.println();

    int[] c = new int[4];
    for (int i = 0; i < 4; i++) {
        c[i] = b[i];
    }
    c = add_three(c);
    for (int i = 0; i < 4; i++) System.out.print(b[i] + " ");
    System.out.println();
    for (int i = 0; i < 4; i++) System.out.print(c[i] + " ");
    System.out.println();
}

}'''

The method 'add_three' should not change the array b's value. The method's result should only be applied to array c. The result I expect is: {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 7}.

enter image description here

But after calling add_three, I could see that both arrays b and c store the result of the method. I heard that when I use arrays as parameters for methods in Java, the reference of the array is called by the method. So I tried to prevent this by copying the parameter as a separate array in the method, but it does not work.

Can anybody explain how this is happening, by how Java works, and any ways to get the results I have actually expected? It would be easier to understand if you can compare Java with C++.

Thanks!

Upvotes: 1

Views: 2326

Answers (1)

JayC667
JayC667

Reputation: 2576

Passing an array is passing a reference. The underlying/targeted array stays the same. Changes in the array itself will be visible everywhere.

C++ copies all its parameters. So C++ will also create TWO complete copies of an array that is passed

  1. INTO a method as parameter
  2. returned from a method via return x;
  3. (and any time you use the assignment operator = for that matter)

In Java, only the reference itself is copied, not the target array.

Thus, you have to create a new array and maybe even copy data to it, depending how you want to use it:

int[] copiedArray = new int[input.length];
System.arraycopy(input, 0, copiedArray, 0, input.length);

As a side note: please NEVER paste code as image, insert it as text just like I did, so others can copy your code if they wanna test it, and don't have to manually re-type everything to help you.

Upvotes: 1

Related Questions