The Wayback Machine - https://web.archive.org/web/20250102200113/https://www.geeksforgeeks.org/multidimensional-arrays-in-java/
Open In App

Java Multi-Dimensional Arrays

Last Updated : 14 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A multidimensional array can be defined as an array of arrays. Data in multidimensional arrays are stored in tabular form (row-major order). 

Example:

Java
// Java Program to Demonstrate
// Multi Dimensional Array
import java.io.*;

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

        int[][] arr = new int[10][20];
        arr[0][0] = 1;

        System.out.println("arr[0][0] = " + arr[0][0]);
    }
}

Output
arr[0][0] = 1

Syntax for Multi-Dimensional Array

data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type[size1][size2]….[sizeN];

Parameters:

  • data_type: Type of data to be stored in the array. For example: int, char, etc.
  • dimension: The dimension of the array created. For example: 1D, 2D, etc.
  • array_name: Name of the array
  • size1, size2, …, sizeN: Sizes of the dimensions respectively.

Examples:

// Two dimensional array:
int[][] twoD_arr = new int[10][20];

// Three dimensional array:
int[][][] threeD_arr = new int[10][20][30];

Size of Multidimensional Arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. 

For example: array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements.

Two – Dimensional Array (2D-Array)

Two – dimensional array is the simplest form of a multidimensional array. A 2-D array can be seen as an array storing multiple 1-D array for easier understanding. 

Syntax (Declare, Initialize and Assigning)

// Declaring and Intializing
data_type[][] array_name = new data_type[x][y];

// Assigning Value
array_name[row_index][column_index] = value;

Representation of 2D Array in Tabular Format

A 2-D array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A 2-D array ‘x’ with 3 rows and 3 columns is shown below: 


Example 1: We can add the values directly to the array while declaring the array.

Java
// Java Program to demonstrate the use of 
// Two Dimensional Array
import java.io.*;

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

          // Array Intialised and Assigned
        int[][] arr = { { 1, 2 }, { 3, 4 } };

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

Output
1 2 
3 4 

Example 2: Here we can update the values while executing works both ways can be accepted by user or by some variable.

Java
// Java Program to demonstrate the use of 
// Two Dimensional Array
public class TwoDArray {
    public static void main(String[] args) {
      
          // Row and Columns in Array
        int n = 2;
        int m = 2;

          // Array declared and initialized
        int[][] arr = new int[n][m];

        int it = 1;
      
          // Assigning the values to array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = it;
                it++;
            }
        }

          // Printing the Array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}

Output
1 2 
3 4 

Accessing Elements of Two-Dimensional Arrays

Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the row number and ‘j’ is the column number. 

Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3.

Example: 

Java
// Java Program to demonstrate Accessing
// Elements of Two-Dimensional Arrays
import java.io.*;

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

        int[][] arr = { { 1, 2 }, 
                           { 3, 4 } };
      
          // Accessing Element at index
          // row=1 and column=1
        System.out.println("a[1][1] : " + arr[1][1]);
    }
}

Output
a[1][1] : 4

Two Dimensional Array with User input

Follow the Steps mentioned below to create a Two Dimensional Array with User input:

  • This code prompts the user to enter the number of rows and columns for the Two-dimensional array. The Scanner class is used to read the user input. Then it creates a Two-dimensional array of integers with the specified number of rows and columns, and assigns each element of the array with i*j.
  • If you want to create a multidimensional array with more than two dimensions, you can use the same approach of creating an array of arrays.

Example:

Java
// Java Program for Creating two
// Dimensional array with user Inputs
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
      
        Scanner scn = new Scanner(System.in);

          // Taking Number of Rows and Columns from User
        System.out.print("Enter number of rows: ");
          int row = scn.nextInt();

        System.out.print("Enter number of columns: ");
        int col = scn.nextInt();

        int[][] arr= new int[row][col];

        // Operating on Two Dimensional Array
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                arr[i][j]= (i + 1) * (j + 1);
            }
        }
      
          // Printing Elements of Arrays
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                System.out.print(arr[i][j]+ " ");
            }

            System.out.println();
        }
        scn.close();
    }
}

Input:

Enter number of rows: 3
Enter number of columns: 3

Output:

1 2 3
2 4 6  
3 6 9  

Three – Dimensional Array (3D-Array)

3D-Array is a complex form of a multidimensional array. A 3D-array can be seen as an array of 2D array for easier understanding. 

Representation of 3D Array in Tabular Format

A three-dimensional array can be seen as a table of arrays with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A three – dimensional array with 3 array containing 3 rows and 3 columns is shown below: 


Example 1: 

Java
// Java Program to Demonstrate
// Three Dimensional Array
import java.io.*;

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

          // Array Created and Initialized
        int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
      
          // Defining the x,y,z in Multi
          // Dimensional Array
          int n = arr.length;
          int m = arr[0].length;
          int o = arr[0][0].length;

        // Printing the Array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++){
              for(int k=0; k < o; k++)
                    System.out.print(arr[i][j][k] + " ");
                System.out.println();
            }
              System.out.println();
        }
    }
}

Output
arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8

Example 2: 

Java
// Java Program to Implement
// Three Dimensional Array
import java.io.*;

class Main {
    public static void main(String[] args){
      
        int[][][] arr = new int[2][2][2];
      
          // Three Dimensional x,y,z dimension
          int n=arr.length;
        int m=arr[0].length;
          int o=arr[0][0].length;
      
          int it=1;
      
        // Assigning the values to array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                  for(int k=0; k < o; k++){
                    arr[i][j][k] = it;
                    it++;
                }
            }
        }

          // Printing the Array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++){
              for(int k=0; k < o; k++)
                    System.out.print(arr[i][j][k] + " ");
                System.out.println();
            }
              System.out.println();
        }
    }
}

Output
1 2 
3 4 

5 6 
7 8 

Accessing Elements of Three-Dimensional Arrays

Elements in three-dimensional arrays are commonly referred by x[i][j][k] where ‘i’ is the array number, ‘j’ is the row number and ‘k’ is the column number. 

Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3. 

Example: 

Java
// Java Program to Demonstrate Accessing
// Three Dimensional Array by Index
import java.io.*;

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

          // Creating an Array
        int[][][] arr = { { { 1, 2 }, { 3, 4 } },
                         { { 5, 6 }, { 7, 8 } } };

          // Printing array at index 0 , 0 , 0
        System.out.println("arr[0][0][0] = " + arr[0][0][0]);
    }
}

Output
arr[0][0][0] = 1

Inserting a Multi-Dimensional Array During Runtime

This topic is forced n taking user-defined input into a multidimensional array during runtime. It is focused on the user first giving all the input to the program during runtime and after all entered input, the program will give output with respect to each input accordingly. It is useful when the user wishes to make input for multiple Test-Cases with multiple different values first and after all those things are done, program will start providing output. Let’s find the total number of even and odd numbers in an input array. Here, we will use the concept of a 2-dimensional array. 

Implementation: 

Java
// Java Program Demonstrating use of
// Multi Dimensional Array
import java.io.*;
import java.util.Scanner;

class Main {
    public static void main(String[] args){
        
          // Scanner class to take
        // values from console
        Scanner scn = new Scanner(System.in);
        
        int n, m;

        // takes total number of
        // TestCases as integer number
        n = scn.nextInt();

        // An array is formed as row
        int[][] arr = new int[n][];

        // for loop to take input of
        // values in each TestCase
        for (int i = 0; i < arr.length; i++) {
            
              // Accepting number of columns
              m = scn.nextInt();
            arr[i] = new int[m];
          
              // Accepting elements in the Two
              // Dimensional Array
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = scn.nextInt();
            }
        }


        for (int i = 0; i < arr.length; i++) {

            int odd = 0, even = 0;

            System.out.println("Rows " + i + " with " + arr[i].length + " Columns");
              System.out.println("Elements of Array:");
          
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");

                // Checking Odd and even numbers
                if (arr[i][j] % 2 == 0) {
                    even++;
                }
                else {
                    odd++;
                }
            }
            System.out.println();

            // Printing even and odd number
            System.out.println("Even: " + even + ", Odd: " + odd);
          
        }
    }
}

Input:

3 3
1 2 3
4 5 6
7 8 9

Output:

Rows 3 with 3 Columns
Elements of Array:
1 2 3 
4 5 6 
7 8 9 
Even: 4, Odd: 5

Application of Multi-Dimensional Array

  • Multidimensional arrays are used to store the data in a tabular form. For example, storing the roll number and marks of a student can be easily done using multidimensional arrays. Another common usage is to store the images in 3D arrays. 
  • In dynamic programming questions, multidimensional arrays are used which are used to represent the states of the problem. 
  • Apart from these, they also have applications in many standard algorithmic problems like:  Matrix Multiplication, Adjacency matrix representation in graphs, Grid search problems.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg