Java
javaTutorial
Transfer mechanism and modification strategy of array parameters in Java methods
Transfer mechanism and modification strategy of array parameters in Java methods

In Java, when objects (including arrays) are used as method parameters, the "value passing" mechanism is used, that is, a copy of the object reference is passed. This means that there is no way inside a method to change the original reference held by the caller by reassigning parameters. However, the method can modify the element contents of the array through this reference, or "replace" the original array by returning a new array and reassigning it by the caller.
Understanding Java's parameter passing mechanism: the essence of value passing
In Java, all parameter passing is "pass-by-value". This core concept is crucial to understanding how methods interact with arrays or other objects.
- Basic data types (such as int, double, boolean, etc.) : When a basic data type is passed as a parameter, the method receives a copy of the value. Any modifications to this copy inside the method will not affect the original variable.
- Object types (including arrays) : When object types (such as String, ArrayList, custom class instances, and arrays) are passed as parameters, the method receives a copy of the object reference . Both this copy reference and the original reference point to the same object in memory. This means:
- Methods can access and modify the object's internal state through this reference copy (for example, changing the values of elements in an array, or calling methods on the object to change its properties).
- However, if the method internally reassigns the parameter to a new object (for example, array = new int[]{...}), this will only change the object pointed to by the method's local parameter, without affecting the original reference held by the caller. The original reference still points to the original object.
Common Mistake: Trying to modify the original reference by reassigning a parameter
Take the following code as an example, which is a typical misunderstanding scenario:
public class ArrayModificationDemo {
public static void modifyArrayReference(int[] array) {
// This line creates a new array object and points the method's local 'array' parameter to it // But it will not affect the object pointed to by 'myArray' in the main method array = new int[]{1, 2, 3, 4, 5};
System.out.println("Inside the method (modifyArrayReference), the third element of the array: " array[2]);
}
public static void main(String[] args) {
int[] myArray = {1, 1, 1, 1, 1};
System.out.println("Before calling, the third element of the array in the main method: " myArray[2]); // Output: 1
modifyArrayReference(myArray);
// Although modifyArrayReference internally reassigns 'array',
// 'myArray' in the main method still points to the original array System.out.println("In the main method, the third element of the array after the call: " myArray[2]); // Still output: 1
}
}
Running results:
Before calling, the third element of the array in the main method: 1 Inside the method (modifyArrayReference), the third element of the array: 3 In the main method, the third element of the array after calling: 1
Explanation: The modifyArrayReference method receives a copy of the myArray reference variable in the main method. When array = new int[]{1, 2, 3, 4, 5}; is executed, it creates a brand new array object and points the array parameter inside the method to this new array. At this time, myArray in the main method still points to the original {1,1,1,1,1} array. Therefore, the main method still prints the third element of the original array, which is 1.
Strategy 1: Modify the element content of the array (modify in place)
If your goal is to modify the contents of the passed-in array, rather than replace the entire array object, you can access and modify the elements of the array directly through the passed-in reference. Since the method parameters and the caller both point to the same array object, modifications to the object will be reflected synchronously.
public class ArrayModificationDemo {
public static void modifyArrayElements(int[] array) {
if (array != null && array.length >= 5) {
array[0] = 10;
array[1] = 20;
array[2] = 30; // Modify the third element array[3] = 40;
array[4] = 50;
}
System.out.println("Inside the method (modifyArrayElements), the third element of the array: " array[2]);
}
public static void main(String[] args) {
int[] myArray = {1, 1, 1, 1, 1};
System.out.println("Before calling, the third element of the array in the main method: " myArray[2]); // Output: 1
modifyArrayElements(myArray);
// At this time, the content of the array pointed to by 'myArray' in the main method has been modified System.out.println("In the main method, the third element of the array after the call: " myArray[2]); // Output: 30
}
}
Running results:
Before calling, the third element of the array in the main method: 1 Inside the method (modifyArrayElements), the third element of the array: 30 In the main method, the third element of the array after calling: 30
Explanation: The array parameter in the modifyArrayElements method and the myArray variable in the main method both point to the same int[] array object in memory. When modifyArrayElements modifies the array element via array[2] = 30;, it directly changes the internal state of that shared object. Therefore, when the main method subsequently accesses myArray[2], it will see the modified value 30.
Strategy 2: Return a new array object
If the method really needs to create an entirely new array and wants the caller to use this new array to replace its original array reference, the method should create the new array and return it. The caller needs to explicitly assign the returned new array to its own reference variable.
public class ArrayModificationDemo {
public static int[] createAndReturnNewArray(int[] originalArray) {
// You can do some processing based on originalArray, or directly create and return a new array int[] newArray = new int[]{1, 2, 3, 4, 5};
System.out.println("Inside the method (createAndReturnNewArray), the third element of the new array: " newArray[2]);
return newArray; // Returns a reference to the newly created array}
public static void main(String[] args) {
int[] myArray = {1, 1, 1, 1, 1};
System.out.println("Before calling, the third element of the array in the main method: " myArray[2]); // Output: 1
// The key step: assign the new array reference returned by the method to myArray
myArray = createAndReturnNewArray(myArray);
// At this point, myArray has pointed to the new array returned by the method System.out.println("In the main method, the third element of the array after the call: " myArray[2]); // Output: 3
}
}
Running results:
Before calling, the third element of the array in the main method: 1 Inside the method (createAndReturnNewArray), the third element of the new array: 3 In the main method, the third element of the array after calling: 3
Explanation: The createAndReturnNewArray method creates a new int[] array and references it as the return value. In the main method, the line myArray = createAndReturnNewArray(myArray); reassigns the myArray variable to a reference to the new array returned by the method. In this way, myArray now points to the new {1,2,3,4,5} array, thus realizing the "replacement" of the array.
Summary and Notes
- Java is always pass-by-value : whether it is a primitive type or an object reference, what is passed is a copy of them.
- Characteristics of reference copies :
- You can use a reference copy to modify the contents of the object it points to (for example, array[index] = value), and this modification is visible to all places that hold references to the object.
- You cannot change the object pointed to by the original reference held by the caller through a reference copy. If you reassign a reference copy inside a method (for example, array = new int[]{...}), this only affects the local reference inside the method, not the caller.
- How to "modify" an array reference :
- Modify elements in place : If the purpose is to change the existing content of the array, just operate the array elements directly through the passed in reference.
- Replace the entire array : If the purpose is to let the caller use a completely new array object, the method should return the new array and the caller should explicitly reassign its reference variable.
- Best practice : When designing a method, make it clear whether the method expects to modify an existing object (in-place) or to create and return a new object. Clear API design helps avoid confusion.
The above is the detailed content of Transfer mechanism and modification strategy of array parameters in Java methods. 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
20528
7
13637
4
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 configure Java's log output environment_Logback and Log4j2 integration solution
Mar 10, 2026 pm 08:39 PM
They cannot be used together - Logback and Log4j2 are mutually exclusive, and SLF4J only allows one binding to take effect; if they exist at the same time, a warning will be triggered and one of them will be randomly selected, resulting in log loss or abnormal behavior. A unified appearance and single implementation are required.
How to hot deploy Java applications in IDEA_JRebel plug-in installation and activation tutorial
Mar 10, 2026 pm 08:01 PM
JRebel has basically failed in modern Java development because of its underlying mechanism conflicts with the Java9 module system, SpringBoot2.4 and mainstream IDEs, while IDEA's built-in HotSwap spring-boot-devtools combination is more stable and reliable.
What is the core role of the collection framework in Java_Analysis of the original intention of Java collection design
Mar 11, 2026 pm 09:01 PM
The core of the Java collection framework is to solve the three major shortcomings of fixed array length, type insecurity, and redundant operations; it abstracts data relationships through interfaces (Collection is a "bundle of things", Map is "mapping rules"), and generics ensure compilation-time type safety, but implementation class switching may cause implicit performance degradation.
How to configure Java hotkeys in IntelliJ IDEA_Common shortcut key customization guide
Mar 10, 2026 pm 08:06 PM
In IDEA, Ctrl Alt L defaults to "ReformatCode", which can be changed to other operations: first check for conflicts in the Keymap, then remove the original binding and add a new shortcut key for the target operation; pay attention to the focus position, file type and plug-in interference; Mac needs to troubleshoot system-level interception; when team collaboration, the Scheme should be unified and the settings should be synchronized with SettingsRepository.
How to deploy Java production environment on Windows Server_Security enhancement and service-oriented configuration
Mar 11, 2026 pm 07:18 PM
The boundary between Java version selection and JRE/JDK must be clearly defined in the production environment. Do not use JDK. JRE must be installed on Windows Server—unless you really need diagnostic tools such as jps and jstack to run in the service process. The java.exe and javaw.exe that come with the JDK have the same behavior, but the extra bin directory in the JDK will increase the attack surface. Especially when misconfigured PATH causes the script to call javac.exe, it may be used to execute compiled malicious payloads. Download the build with jdk-xx.jre suffix from https://adoptium.net/ (such as temurin-17.0.2 8-jre), which is not the jdk package installation path.
JavaFX: Copy string contents to system clipboard
Mar 13, 2026 am 04:12 AM
This article details how to copy string contents to the system clipboard in a JavaFX application. By utilizing the javafx.scene.input.Clipboard and javafx.scene.input.ClipboardContent classes, developers can easily implement clipboard operations on text data. The article provides clear sample code and usage guidelines to ensure that readers can quickly master and apply this feature in their own projects to improve user experience.
Optimize the Controller layer: introduce DTO mapping and service calling abstraction layer
Apr 03, 2026 am 10:00 AM
This article discusses the introduction of an abstraction layer between the Controller and business services in order to solve the problems of overloaded responsibilities and code duplication in the Controller layer in Web application development. This layer is mainly responsible for the mapping of request DTOs and service input DTOs, service calls, and the mapping of service output DTOs and response DTOs. It achieves generalization through generic and functional programming, thereby improving the cleanliness, maintainability and testability of the code.





