In JAVA, for Arrays, what works: passed by value OR reference?
- TechPro
- Sep 22
- 2 min read
In Java, arrays are passed by value, but this value is a reference to the array object. This can be a tricky concept. Let's break it down.
The Key Distinction
When you pass an array to a method, you're not passing the entire array's data. Instead, you're passing a copy of the memory address (the reference) where the array object lives.
Pass by Value: The method receives a copy of the argument. Any changes made to this copy inside the method do not affect the original argument in the calling method.
Pass by Reference: The method receives the memory address of the argument. Changes made to the object through this address affect the original object.
So, in Java, you have a pass-by-value of the reference. This means:
You can't change which array the original variable refers to from within the method. If you reassign the parameter to a new array object, the original variable outside the method is unchanged.
You can modify the contents (the elements) of the array. Since the copied reference points to the same object in memory, any changes you make to the elements of the array inside the method will be visible outside the method.
Example
Consider this code JAVA code snippet:
public class ArrayPasser {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3};
System.out.println("Before method call: " + originalArray[0]); // Prints 1
modifyArray(originalArray);
System.out.println("After method call: " + originalArray[0]); // Prints 100
}
public static void modifyArray(int[] arr) {
// This modifies the content of the original array
arr[0] = 100;
// This reassigns the local 'arr' variable to a new array
// It DOES NOT affect the 'originalArray' variable outside this method
arr = new int[] {4, 5, 6};
System.out.println("Inside method after reassignment: " + arr[0]); // Prints 4
}
}
In this example, originalArray is passed to modifyArray.
When modifyArray is called, a copy of the reference to {1, 2, 3} is passed. Both originalArray and arr now point to the same object.
arr[0] = 100 changes the first element of the object that both references point to. The original array is now {100, 2, 3}. This is why the output is 100.
arr = new int[] {4, 5, 6} creates a new array object. The arr variable is now a reference to this new object. The original originalArray variable, however, still refers to the first array. This is why the first println statement after the method call still shows the modified value 100.

Comments