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) } }
In this example:
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!