Changing array in method changes array outside
java, scope, variables
Solution
An array in Java is an object. When you create an array via `new`, it's created on the heap and a reference value (analogous to a pointer in C) is returned and assigned to your variable.
In C, this would be expressed as:
int *array = malloc(10 * sizeof(int));
When you pass that variable to a method, you're passing the reference value which is assigned (copied) to the local (stack) variable in the method. The contents of the array aren't being copied, only the reference value. Again, just like passing a pointer to a function in C.
So, when you modify the array in your method via that reference, you're modifying the single array object that exists on the heap.
You commented that you made a "copy" of the array via `int[] temp=test` ... again, this only makes a copy of the reference value (pointer) that points to the single array in memory. You now have three variables all holding the same reference to the same array (one in your `main()`, two in your method).
If you want to make a copy of the array's contents, Java provides a static method in the `Arrays` class:
int[] newArray = Arrays.copyOf(test, test.length);
This allocates a new array object on the heap (of the size specified by the second argument), copies the contents of your existing array to it, then returns the reference to that new array to you.
Problem
I have trouble with scope of variable. ``` public static void main(String[] args){ int[] test={1,2,3}; test(test); System.out.println(test[0]+" "+test[1]+" "+test[2]); } static void test(int[] test){ test[0]=5; } ``` I expected the output to `1 2 3`, but the result was `5 2 3`. Why I changed the value in the array in the method, but the original array changed?