Home > Java > javaTutorial > Are Java Arrays Passed by Value or by Reference?

Are Java Arrays Passed by Value or by Reference?

Barbara Streisand
Release: 2024-12-16 19:02:12
Original
887 people have browsed it

Are Java Arrays Passed by Value or by Reference?

Understanding Value and Reference Passing in Java Arrays

In Java, the concept of "pass by value" and "pass by reference" is frequently discussed. This article aims to shed light on whether arrays are passed by value or reference.

Contrary to popular belief, arrays in Java are not considered primitive types, nor are they objects. Therefore, the question arises: How are arrays handled during passing?

The answer is unequivocal: Everything in Java is passed by value. When an array is passed as an argument to another method, what is actually passed is the reference to that array. This is analogous to the way object references are passed by value.

Any modifications made to the content of an array through the passed reference will subsequently affect the original array. However, altering the reference itself to point to a different array will not have any impact on the existing reference in the original method.

To illustrate this concept, consider the following example:

public static void changeContent(int[] arr) {

   // If we change the content of arr.
   arr[0] = 10;  // Will change the content of array in main()
}

public static void changeRef(int[] arr) {
   // If we change the reference
   arr = new int[2];  // Will not change the array in main()
   arr[0] = 15;
}

public static void main(String[] args) {
    int [] arr = new int[2];
    arr[0] = 4;
    arr[1] = 5;

    changeContent(arr);

    System.out.println(arr[0]);  // Will print 10.. 

    changeRef(arr);

    System.out.println(arr[0]);  // Will still print 10.. 
                                 // Change the reference doesn't reflect change here..
}
Copy after login

In this example, when arr is passed to changeContent, the content of arr is modified (i.e., arr[0] is assigned the value 10). This change affects the original arr variable in main. However, when arr is passed to changeRef, the reference itself is modified by assigning a new array to it. Consequently, this change does not affect the original arr variable in main.

The above is the detailed content of Are Java Arrays Passed by Value or by Reference?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template