Home > Java > javaTutorial > Java Arrays: Pass by Value or Pass by Reference?

Java Arrays: Pass by Value or Pass by Reference?

Susan Sarandon
Release: 2024-12-29 08:03:14
Original
548 people have browsed it

Java Arrays: Pass by Value or Pass by Reference?

Java Arrays: Value or Reference Passing?

Arrays in Java hold a special status, being neither primitive types nor full-fledged objects. This unique nature raises the question: are Java arrays passed by value or by reference?

Everything in Java is passed by value. This includes arrays. When you pass an array to a method, what is actually passed is the reference to that array, not the array itself.

Therefore, any modifications made to the contents of the array through that reference will impact the original array. However, altering the reference to point to a new array won't affect the reference held in the original method.

Consider the following Java snippet:

public class ArrayPassingDemo {

    public static void changeContent(int[] arr) {
        arr[0] = 10; // Changes the content of the array in main()
    }

    public static void changeRef(int[] arr) {
        arr = new int[2]; // Does 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 (since the reference change isn't reflected)
    }
}
Copy after login

In this example:

  • changeContent modifies the array's contents, which is reflected in main().
  • changeRef attempts to change the array reference but fails, as the original reference remains unaffected in main().

This behavior highlights that arrays in Java are passed by value, even though the passing operation involves their reference.

The above is the detailed content of Java Arrays: Pass by Value or Pass 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