Introduction to 2-D Arrays in Java

Introduction to 2D Arrays in Java

Multidimensional Arrays can be defined in simple words as an array of Arrays in Java. Data in multidimensional arrays are stored in tabular form (in row-major order).

The 2D array is organized as matrices which can be represented as the collection of rows and columns.

Syntax :

The syntax of declaring a two-dimensional array is very much similar to that of a one-dimensional array, given as follows.

datatype variable_name[rows][column]

Example: int[ ][ ]  arr = new int[20][20];

array in java

How do we access data in a 2D array?

The elements of 2D arrays can be randomly accessed. Similar to one-dimensional arrays, we can access the individual cells in a 2D array by using the indices of the cells. There are two indices attached to a particular cell, one is its row number while the other is its column number.

we can store the value stored in any particular cell of a 2D array to some variable a by using the following syntax.

int a = x[i][j]

where x is row index and j is column index 

Initializing 2D Arrays

  •  DIRECT METHOD

data_type[][] variable_name = { {R1C1, R1C2, ….}, {R2C1,R2C2, ….} };

Example: 

int [ ][ ] arr = { { 2 ,  4 } ,  {6, 8 } };

  • USING LOOPS:

We can use loops for initializing 2d array like

for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
int a = x[i][j];
}
}

JAVA CODE TO SHOW HOW TO INITIALIZE AND PRINT  2-D ARRAY:

Run
class Main
{ 
    public static void main(String[] args) 
    { 

        int[][] arr = { { 2, 4 }, { 6, 8 } }; 

        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                    System.out.print(arr[i][j] +" ");
            }
            System.out.println();
        }
    } 
}

Output:

 2 4
 6 8 

One comment on “Introduction to 2-D Arrays in Java”


  • suraj

    public static void main(String args[]) {
    System.out.println(“Hello World!”);

    int[][] arr = new int[][] { { 2, 4 }, { 6, 8 } };

    for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++)
    System.out.print(arr[i][j] +" ");
    System.out.println();}

    }