Passing and Returning an Array

In Java, arrays are objects, and they can be passed to methods just like any other object. Understanding how to pass and return arrays is essential for managing data in your programs.

Passing an Array to a Method

When you pass an array to a method, you’re actually passing a reference to the array, not the array itself. This means changes made to the array inside the method affect the original array outside the method.

Example: Passing an Array

Output

As shown, the first element of the array was modified inside the modifyArray() method.

Returning an Array from a Method

You can return an array from a method just like returning any other object. The method will return a reference to the array, not a copy, allowing you to work with the array in the calling code.

Example: Returning an Array

Output

The method getArray() returns a new array, and we can use it in the main() method.