Pass 2d Array to Method in Java

Published by user on

In this post, we will look at the way to pass a 2d array to a method in Java. We will also look at how to return it.

Program to Pass 2d Array to function:

public class Pass2dArray {
        public static void main(String[] args) {
                int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
                acceptIt(a); // pass it to the method
        }

        public static void acceptIt(int[][] a) {
                System.out.println("Elements are :");

                for (int i = 0; i < a.length; i++) {
                        for (int j = 0; j < a[i].length; j++) {
                                System.out.print(a[i][j] + "\t");
                        }
                        System.out.println("");
                }
        }
}

Output:

Elements are :
1       2       3
4       5       6
7       8       9

We passed a 2d array to a method and printed it. Whatever changes you make to array in the method are reflected in the main().

Return a two dimensional Array from a method:

public class ReturnTwoDimensionalArray {
        public static void main(String[] args) {
                int b[][] = returnIt();
                System.out.println("Length is : " + b.length);
        }

        // returns a 2d array
        public static int[][] returnIt() {
                int[][] b = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
                return b;
        }
}

Output:

Length is : 3

In the above program, we returned a two-dimensional array from a method.

As we saw it is very simple to pass or return multidimensional array to/from the method.

That’s all for this article. Please share the article if you like it.

Categories: Java