Methods and Arrays in Java

Methods and arrays go hand in hand in programming. You will frequently be using methods along with arrays: whether it is to pass an array to a method or return an array from a method, you will be dealing with them quite often.


1. Passing an array to a method

There are times when you want to manipulate a collection of data within a method. In those scenarios you can pass the reference of an array to a method. It is efficient as only the reference is passed and not the actual data .

Output :

The method do_squares in the above program takes an array, and modifies the array. The modifications are visible from outside this method because the method modified the same copy.


2. Returning an array from a method

There are times when you want to return a collection of data from a method. In those cases you can pack your data inside an array and return the reference of that array from your method.

Output :

Note: Since the memory allocation for arrays happens dynamically using new keyword, you don’t have to worry about data loss when a method returns. This is because all dynamic memory allocation happens on heap section of the memory and not on the stack.


3. Anonymous arrays in Java

Anonymous arrays have no names. They are generally used along with methods(but not always). They can be created on the go using the new keyword. For example: to create an anoymous array of doubles you write  new double[]{2.0, 4.5, 7.1, 8.3, 9.7}; .

Output :

The method do_squares in the above program takes an array, modifies the array and returns the same modified array.


4. Multi-dimensional arrays and methods

Since you can have arrays of multi-dimensions, you can do compuations on them inside a method as well. Lets see one for a two-dimensional array.

Output :

Similarly you can return a two-dimensional array from a method.