Java
javaTutorial
In-depth analysis of Java method parameter passing: array reference and value passing mechanism
In-depth analysis of Java method parameter passing: array reference and value passing mechanism

Java uses a value passing mechanism to handle all method parameters. For object types (including arrays), a copy of the object reference is passed. This means that reassigning the parameter reference inside the method to point to a new object does not affect the original reference in the caller. If you need to change the object referenced by the caller, you must modify the original object content within the method, or return a new object and reassign it by the caller.
Understand Java’s method parameter passing mechanism
Java always follows the principle of "pass-by-value" when processing method parameters. This core mechanism is critical to understanding code behavior, especially when it comes to objects and arrays.
- Basic data types (such as int, double, boolean, etc.): When a variable of a basic data type is passed as a parameter, a copy of the variable value is passed. Any modification to the parameters inside the method will only affect this copy, not the original variable.
- Object type (including array): When an object reference (such as String, Object, int[], etc.) is passed as a parameter, a copy of the object reference is passed. This means that the parameter variables inside the method and the original variables outside initially point to the same object in the heap memory. Modifications to the internal state of this shared object will be reflected externally; but if the parameter reference is reassigned internally in the method so that it points to a new object, then this will only change the pointing of the local parameters and will not affect the pointing of the external original reference.
Common misunderstandings when passing arrays by reference
To better illustrate the behavior of object references when passed as parameters, let's look at a typical example that often causes confusion for beginners:
public class ArrayPassByValueExample {
public static void modifyArrayReference(int[] arrayParam) {
//Print the state before modification of the internal parameters of the method if (arrayParam != null && arrayParam.length > 0) {
System.out.println("Internal method (modifyArrayReference) - before reassignment, arrayParam[0] = " arrayParam[0]);
}
// This line of code creates a new array object {1, 2, 3, 4, 5}
//And point the local reference variable arrayParam to the newly created array arrayParam = new int[]{1, 2, 3, 4, 5};
System.out.println("Internal method (modifyArrayReference) - after reassignment, arrayParam[2] = " arrayParam[2]);
}
public static void main(String[] args) {
int[] originalArray = {1, 1, 1, 1, 1};
System.out.println("Before calling the modifyArrayReference method: originalArray[2] = " originalArray[2]); // Expected output 1
modifyArrayReference(originalArray);
System.out.println("After calling the modifyArrayReference method: originalArray[2] = " originalArray[2]); // The actual output is 1, not 3
}
}
Code behavior analysis:
- In the main method, the originalArray variable is initialized, which refers to an int array object {1, 1, 1, 1, 1} in the heap memory. At this time, the value of originalArray[2] is 1.
- When modifyArrayReference(originalArray) is called, a copy of the reference to originalArray is passed to the arrayParam parameter of the modifyArrayReference method. At this time, both originalArray and arrayParam point to the same {1, 1, 1, 1, 1} array object in the heap memory.
- Entering the modifyArrayReference method, arrayParam = new int[]{1, 2, 3, 4, 5}; This line of code performs two key operations:
- First, it creates a brand new int array object {1, 2, 3, 4, 5} in heap memory.
- Then, it points the reference of the local variable arrayParam to the newly created array.
- The key point is this: the reference to originalArray never changes. It still points to the original {1, 1, 1, 1, 1} array. And arrayParam only has its local reference repointed to a new array.
- Therefore, when the main method accesses originalArray[2] again after modifyArrayReference is called, it still accesses the original array, and its value is still 1, not 3 in the new array created inside the modifyArrayReference method.
How to efficiently modify an array or its reference in a method
If our goal is to have a method affect an external array, or have an external variable point to a new array created within the method, we need to adopt a different strategy.
Strategy 1: Modify the internal elements of the array (without changing the reference point)
If the purpose is to modify the contents of the array rather than letting the external variable point to a brand new array, you can directly operate on the passed array parameters. Since the parameter reference and the external reference point to the same array object, any modification to the contents of the object will be reflected externally.
public class ArrayModificationExample {
public static void modifyArrayContent(int[] arrayParam) {
// Directly modify the elements of the passed array if (arrayParam != null && arrayParam.length >= 5) {
arrayParam[0] = 10;
arrayParam[1] = 20;
arrayParam[2] = 30; // Change the third element to 30
arrayParam[3] = 40;
arrayParam[4] = 50;
}
System.out.println("Access inside method (modifyArrayContent): arrayParam[2] = " arrayParam[2]);
}
public static void main(String[] args) {
int[] originalArray = {1, 1, 1, 1, 1};
System.out.println("Before calling the modifyArrayContent method: originalArray[2] = " originalArray[2]); // Output 1
modifyArrayContent(originalArray);
System.out.println("After calling the modifyArrayContent method: originalArray[2] = " originalArray[2]); // Output 30
}
}
In this example, the modifyArrayContent method directly modifies the contents of the array object pointed to by arrayParam. Since originalArray also points to the same object, after the main method calls modifyArrayContent, the value of originalArray[2] successfully changes to 30.
Strategy 2: Return the new array and reassign the value (change the reference point)
If you really need to create a brand new array inside the method and want the caller variable to point to this new array, then the method needs to return the new array and assign the return value to the corresponding variable in the caller.
public class ArrayReturnExample {
public static int[] createAndReturnNewArray(int[] arrayParam) {
//Create a new array object and return int[] newArray = new int[]{1, 2, 3, 4, 5};
System.out.println("Access inside method (createAndReturnNewArray): newArray[2] = " newArray[2]);
return newArray;
}
public static void main(String[] args) {
int[] originalArray = {1, 1, 1, 1, 1};
System.out.println("Before calling the createAndReturnNewArray method: originalArray[2] = " originalArray[2]); // Output 1
//Assign the new array returned by the method to originalArray
originalArray = createAndReturnNewArray(originalArray);
System.out.println("After calling the createAndReturnNewArray method: originalArray[2] = " originalArray[2]); // Output 3
}
}
In this way, the originalArray variable in the main method is successfully reassigned after calling createAndReturnNewArray, pointing to the new array created in the method. At this time, the value of originalArray[2] also changes to 3.
Summary and Notes
- Java is always pass by value. Understanding this basic principle is key to avoiding such confusion.
- For object references, a copy of the reference is passed. This means that method parameters and original variables initially point to the same object in heap memory.
- Reassigning parameter references within a method (such as param = new Object() or param = someOtherObject) will only change the pointing of local parameters and will not affect the pointing of external original references. External variables still refer to the original object.
- To change the contents of an object referenced by an external variable, you can directly manipulate the object through a parameter reference (for example, param[index] = value or param.setField(value)). This modification will be reflected externally.
- For an external variable to refer to a new object, the method must return the new object and explicitly reassign it at the call site (for example, originalVar = methodCall()).
- When designing a method, be clear about whether the method will modify an existing object ("mutator") or return a new object ("factory" or "transformer"). This can help improve the readability and maintainability of the code and avoid unnecessary confusion.
The above is the detailed content of In-depth analysis of Java method parameter passing: array reference and value passing mechanism. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips
Mar 06, 2026 am 06:24 AM
Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
How to safely read a line of integer input in Java and avoid Scanner blocking
Mar 06, 2026 am 06:21 AM
This article introduces typical blocking problems when using Scanner to read multiple integers in a single line. It points out that hasNextInt() will wait indefinitely when there is no subsequent input, and recommends a safe alternative with nextLine() string splitting as the core.





