Multidimensional Array in Java

Multidimensional Array

An array with more than one dimension is known as a multidimensional array.

A multidimensional array is an array of arrays. for example, a 2D array is a collection of the 1D array. A 3D array is a collection of 2D arrays put together with a 1D array.

2d array in java

2D Array Declaration

2D arrays are like matrices, collections of rows and columns. We can declare a 2D array in java in the following ways-

2D Array Declaration Syntax

int[][] arrayName = new int [length of row] [length of column];

OR

int arrayName[][] = new int[length of row][length of column];

2D Array Declaration Example Java

int[][] array = new int [2][3]; // matrix of 2 *3

OR

int array[][] = new int[4][5]; matrix of 4*5

2D Array Initialization

we can initialize a 2D array in the following way

int array[2][3] = {{1,2,3},{4,1,6}};

Size of 2D Array

Size of a 2d array is calculted by multiplying length of row and column. For example size of Array[2][5] is 10 i.e., this array can store 10 elements in 2 rows and 5 column.

2D Array Input in Java

for taking input for 2D array, 2 loop is required. First loop is for rows and 2nd loop is for column. in this way value is assigned to every column in a row

Java code to take input for 2D array

package gangforcode;

import java.util.Scanner;

public class Array2D {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int array2D[][] = new int[3][4]; // 2d array declaration 3 row & 4 Column
        
        // loop for taking input for 2d array
        
        for(int i=0;i<3;i++) // for loop for row
        {
            for(int j=0;j<4;j++)  // for loop for column
            {
                array2D[i][j] = sc.nextInt();
            }
        }
        
    }
}

Java Code for printing 2D Array

package gangforcode;

import java.util.Scanner;

public class Array2D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int array2D[][] = new int[3][4]; // 2d array declaration 3 row & 4 Column

// loop for taking input for 2d array

for(int i=0;i<3;i++) // for loop for row
{
for(int j=0;j<4;j++) // for loop for column
{
array2D[i][j] = sc.nextInt();
}
}


// printing 2D Array
System.out.println("Elements entered in Array");

for(int i=0;i<3;i++) // for loop for row
{
for(int j=0;j<4;j++) // for loop for column
{
System.out.print(array2D[i][j]+" ");
}
System.out.println();
}

}
}

output for 2d array

2d array input

You can also check video of 2D Array input in java

Similar Java Tutorials

6 thoughts on “Multidimensional Array in Java”

Leave a Comment