Javatpoint Logo
Javatpoint Logo

How to Return a 2D Array in Java?

In Java, returning a 2D array from a method can be a useful operation when dealing with complex data structures or performing various data manipulation tasks. In this section, we will delve into the details of how to return a 2D array in Java, providing step-by-step explanations and complete code examples.

2D Arrays in Java

Before we dive into the code, let's understand what a 2D array is in Java. A 2D array is essentially an array of arrays. It can be thought of as a grid or a matrix where each element is accessed using two indices: row and column. In Java, 2D arrays are declared and initialized as follows:

Here, the datatype is the type of data the array will hold, arrayName is the name of the array, rows is the number of rows, and columns are the number of columns.

Method 1: Returning and Printing a 2D Integer Array


2D Integer Array:
46 26 28 45 
60 63 61 56 
69 91 81 43

Method 2: Returning and Printing a 2D String Array


2D String Array:
Row 0, Col 0 Row 0, Col 1 Row 0, Col 2 
Row 1, Col 0 Row 1, Col 1 Row 1, Col 2

Method 3: Returning and Printing a 2D Custom Object Array


2D Custom Object Array:
Object at Row 0, Col 0 Object at Row 0, Col 1 
Object at Row 1, Col 0 Object at Row 1, Col 1

Returning a 2D Array with Different Data Types

If we need to return a 2D array of a different data type (for example, String, double, or custom objects), we can simply replace the int type with the desired data type in the method definition and adjust the data population logic accordingly.


Returning a 2D array in Java involves defining a method with a 2D array return type, initializing and populating the array within the method, and finally returning the filled 2D array. The capability can be invaluable when working with complex data structures or performing data manipulation tasks that require multi-dimensional arrays. Remember to adjust the data type and population logic according to your specific requirements, as demonstrated in the examples provided.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA