When an array is passed to a method in Java, the method receives a copy of the reference (memory address) to the original array, not a copy of the entire array itself. This means the method works with the same array object in memory, so any modifications to the array elements inside the method will affect the original array outside the method
. Key points:
- Java is strictly pass-by-value, but for arrays (which are objects), the "value" passed is the reference to the array object
- The method parameter receives a copy of this reference, so both the caller and the method refer to the same array instance
- Changes to the array's elements inside the method will be visible to the caller because they share the same underlying array
- However, reassigning the array parameter inside the method to a new array does not affect the caller's reference
Example method signature accepting an array:
java
public static void testArray(int[] num) {
// num refers to the same array passed in
}
Calling this method with an array passes the reference by value:
java
int[] myArray = {1, 2, 3};
testArray(myArray); // method receives a copy of the reference to myArray
Any changes to num[i]
inside testArray
modify the original myArray
elements. In summary, the method receives a copy of the reference to the
original array, allowing it to modify the array elements directly, but the
reference itself is passed by value