Passing Two-Dimensional Arrays to Methods

Paul Ngugi - May 29 - - Dev Community

When passing a two-dimensional array to a method, the reference of the array is passed to the method. You can pass a two-dimensional array to a method just as you pass a one-dimensional array. You can also return an array from a method. The program below gives an example with two methods. The first method, getArray(), returns a two-dimensional array, and the second method, sum(int[][] m), returns the sum of all the elements in a matrix.

Image description

Enter 3 rows and 4 columns:
1 2 3 4
5 6 7 8
9 10 11 12
Sum of all elements is 78

The method getArray prompts the user to enter values for the array (lines 13–25) and returns the array (line 24). The method sum (lines 27–36) has a two-dimensional array argument. You can obtain the number of rows using m.length (line 29) and the number of columns in a specified row using m[row].length (line 30).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .