Tutorial Playlist
An array is a data structure storing similar data types in adjoining memory locations. The concept of multidimensional arrays strikes up when the elements inside an array are also arrays themselves. Multidimensional arrays are supported in Java and can get five or more levels deep in a tabular form.
An array collects data of similar types and stores them in contiguous memory locations. Numerous arrays in an array make up a multidimensional array. For example, putting a bunch of 1D arrays in an array creates a 2D array. Similarly, a 3D array is formed by placing 2D arrays together in a 1D array. Arrays store their data in a tabular form or row-major format. They can vary from 1-dimensional to N-dimensional.
Commonly used forms of multidimensional arrays in Java are 2D arrays, 3D arrays, 4D arrays, etc., where D stands for the dimension. With higher dimensions, accessing and storing elements become more difficult. Depending on the elements and array dimension, you can use multiple ways to initialize and declare a multidimensional array in Java.
The operations performed on multidimensional arrays become more challenging with the increasing dimensions. You can add, subtract, multiply, and execute several other activities on a multidimensional array system.
In Java, multidimensional arrays are extensively used for various applications. Here are some applications of multi-dimensional arrays in Java:
Here is the syntax for creating and manipulating multidimensional arrays in Java:
dataType[][] arrayName = new dataType[rows][columns];
Now, let us break the syntax down and understand the keywords:
For accessing and modifying elements in the multidimensional array, we can then use square brackets ([]) to specify the indices for each dimension.
Here is an example:
arrayName[rowIndex][columnIndex] = value;
The above example is still a 2-D array. We can add more than two dimensions by adding additional pairs of square brackets. For instance, a 3D array with dimensions x, y, and z would be declared as follows:
dataType[][][] arrayName = new dataType[x][y][z];
Now, let us look at a working example of a multidimensional array in Java:
public class Main {
  public static void main(String[] args) {
    // Declare and initialize a 2D array
    char[][] grid = {
      {'A', 'B', 'C'},
      {'D', 'E', 'F'},
      {'G', 'H', 'I'}
    };
    Â
    // Access and modify elements in the array
    char element = grid[1][2];  // Accessing the element at row 1, column 2
    System.out.println("Element at row 1, column 2: " + element);
    Â
    grid[0][1] = 'X';  // Modifying the element at row 0, column 1
    Â
    // Display the array
    for (int i = 0; i < grid.length; i++) {
      for (int j = 0; j < grid[i].length; j++) {
        System.out.print(grid[i][j] + " ");
      }
      System.out.println();  // Move to the next row
    }
  }
}
In the above example, a 2D array grid represents a 3x3 grid of characters. We access and modify elements using the indices row and column and then display the modified array using nested for loops.
In this example of a multidimensional array of primitive types, we will create a 2D array of integers (int) called matrix with dimensions 3x3. We will then assign values to specific elements of the array using the row and column indices. Finally, we print the values of three elements of the array.
public class main {
  public static void main(String[] args) {
    int[][] matrix = new int[3][3];
    matrix[0][0] = 1;
    matrix[1][1] = 2;
    matrix[2][2] = 3;
    System.out.println(matrix[0][0]);  // Output: 1
    System.out.println(matrix[1][1]);  // Output: 2
    System.out.println(matrix[2][2]);  // Output: 3
  }
}
In this example of a multidimensional array of objects, we will create a 2D array of strings (String) called names with dimensions 2x2. We will then assign names to different array elements using the row and column indices. Then, we print the values of two elements of the array.
public class main {
  public static void main(String[] args) {
    String[][] names = new String[2][2];
    names[0][0] = "John";
    names[0][1] = "Doe";
    names[1][0] = "Jane";
    names[1][1] = "Smith";
    System.out.println(names[0][0]);  // Output: John
    System.out.println(names[1][1]);  // Output: Smith
  }
}
In this example of a multidimensional array of arrays, we will create a 2D array where each element is another 1D array. The matrix variable is a 2D array with dimensions 3x3, where each row is a 1D array of integers. We will access and print the values of specific elements using the row and column indices.
public class main {
  public static void main(String[] args) {
    int[][] matrix = {
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
    };
    System.out.println(matrix[0][0]);  // Output: 1
    System.out.println(matrix[1][2]);  // Output: 6
    System.out.println(matrix[2][1]);  // Output: 8
  }
}
In this example of a multidimensional array of custom objects, we will create a custom class called Person, representing a person with a name and an age. In the main method, we will declare and initialize a 2D array of Person objects called people. The array will have dimensions 2x2, meaning it can hold 4-person objects.
class Person {
  private String name;
  private int age;
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  public String getName() {
    return name;
  }
  public int getAge() {
    return age;
  }
}
public class main {
  public static void main(String[] args) {
    Person[][] people = new Person[2][2];
    people[0][0] = new Person("John", 25);
    people[0][1] = new Person("Jane", 30);
    people[1][0] = new Person("Mike", 40);
    people[1][1] = new Person("Lisa", 35);
    System.out.println(people[0][0].getName());  // Output: John
    System.out.println(people[1][1].getAge());  // Output: 35
  }
}
Let us look at a more complex multidimensional array example where we work with a 3D array representing a cube structure.
public class main {
  public static void main(String[] args) {
    // Declare and initialize a 3D array
    int[][][] cube = {
      {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
      },
      {
        {10, 11, 12},
        {13, 14, 15},
        {16, 17, 18}
      },
      {
        {19, 20, 21},
        {22, 23, 24},
        {25, 26, 27}
      }
    };
    Â
    // Access and modify elements in the array
    int element = cube[1][2][0];  // Accessing the element at level 1, row 2, column 0
    System.out.println("Element at level 1, row 2, column 0: " + element);
    Â
    cube[2][1][2] = 30;  // Modifying the element at level 2, row 1, column 2
    Â
    // Display the array
    for (int level = 0; level < cube.length; level++) {
      System.out.println("Level " + level + ":");
      for (int row = 0; row < cube[level].length; row++) {
        for (int column = 0; column < cube[level][row].length; column++) {
          System.out.print(cube[level][row][column] + " ");
        }
        System.out.println();  // Move to the next row
      }
      System.out.println();  // Add a line break between levels
    }
  }
}
In this example, we have a 3D array called cube that represents a cube structure with three levels, each with three rows and three columns. The array is initialized with the provided values.
We access and modify elements of the array using the indices for each dimension. For example, cube[1][2][0] refers to the element at level 1, row 2, column 0. We store the accessed element in the element variable and print it.
We also demonstrate modifying an element by assigning a new value to cube[2][1][2], which refers to the element at level 2, row 1, column 2. We change its value to 30.
We use nested for loops to iterate through each level, row, and column of the cube array to display the array. We print the elements and add appropriate line breaks to maintain the cube structure in the output.
Multidimensional arrays are made of homogenous data structures that can store similar categories of data, namely an array. They are efficient at storing data in tabular forms, although the complexity of accessing the internal elements increases with more dimensions. The prevalent forms of multidimensional arrays in Java are the 2D and 3D arrays, broadly used in games, software, mathematical analysis, and graphics.
Through this tutorial, you can gain a comprehensible insight into a multidimensional array in Java and learn about its aspects. You can check out various courses on Java from upGrad to build up your expertise and improve your understanding of Java concepts.
1. How many types of multidimensional arrays are there in Java?
Java can support five or more levels of multidimensional arrays. The typically used dimensions of arrays include the two-dimensional or 2D array and the three-dimensional or 3D array since the higher levels of a multidimensional array are more difficult to work with.
2. What is the limit of a multidimensional array in Java?
Java can work with 5D or more dimensions of arrays. The size allocation of a Java program usually depends on the JVM and the platform. An approximate estimation based on calculations states that an array can theoretically include 2,147,483,647 elements.
3. How to loop a two-dimensional array in Java?
You can loop a 2D array in Java using two for loops, commonly known as a nested loop. Using a similar technique, you will need N-loops nested into each other to loop an N-dimensional array.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...