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.
The value of variable b is never changed; the method's result is only applied to variable c.
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}.
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!