Multi-Dimensional Arrays in Java

Multi-Dimensional Arrays :- In Java, a multi-dimensional array is simply an array of arrays. It allows you to storing data in a tabular format or matrix likely format. While the most common used multi-dimensional array is the 2D array, Java supports higher-dimensional arrays like 3D or 4D arrays.

 

Syntax for Multi-Dimensional Arrays:-

Here’s how we declare and initialize a multi-dimensional array in Java with example:-

// Declaration of a 2D array(Syntax)
dataType[][] arrayName;

// Example of A 2D array 
int[][] numbers = new int[3][4]; // 3 rows and 4 columns

//another method of initialize 
int[][] numbers =
 {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

This is initialization and declaration of  2D array.

3D Arrays :-

A 3D array is  a collection of 2D arrays. we can visualize it as multiple layers of tables stacked on top of each other in 3D arrays.

Syntax:-

//synyax od 3D array
int[][][] array = new int[2][3][4]; // 2 layers, 3 rows, 4 columns in each row

Accessing Elements in a 3D Array:-

//example of accessing element in 3D arrays

array[0][1][2] = 10; // Access element in 1st layer, 2nd row, 3rd column
System.out.println(array[0][1][2]); 
output:- 10

Example of Multi-Dimensional Arrays:- to store students marks.

//example to store student marks.
public class StudentGrades {
    public static void main(String[] args) {
        int[][] grades = {
            {85, 90, 78, 92}, // Student 1
            {88, 76, 95, 89}, // Student 2
            {90, 88, 84, 91}  // Student 3
        };

        for (int i = 0; i < grades.length; i++) {
            System.out.print("Student " + (i + 1) + " Grades: ");
            for (int j = 0; j < grades[i].length; j++) {
                System.out.print(grades[i][j] + " ");
            }
            System.out.println();
        }
    }
}
output :- 

Student 1 Grades: 85 90 78 92
Student 2 Grades: 88 76 95 89 
Student 3 Grades: 90 88 84 91

 

Advantages of Multi-Dimensional Arrays :-

  • Efficient Storage:
    Helps in storing large volumes of related data in a structured way.
  • Data Representation:
    Useful for representing tables, grids, and matrices in program.
  • Simplifies Operations:
    Makes it easier to perform operations like traversals, searching, or sorting on tabular data.

 

 
Conclusion :-

Multi-dimensional arrays in Java are powerful tools for organizing and managing complex data structures. While 2D arrays are primarily used for representing tabular or matrix-like data, 3D arrays extend this capability to store hierarchical data across multiple dimensions.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top