top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Multidimensional Array in Java

Overview

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. 

Introduction to Multidimensional Array in Java

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. 

Application of Multidimensional Array

In Java, multidimensional arrays are extensively used for various applications. Here are some applications of multi-dimensional arrays in Java:

  • Matrix Operations: Multi-dimensional arrays in Java often perform matrix operations. Matrices can be represented as two-dimensional arrays. Operations like matrix multiplication, addition, subtraction, and transposition can be implemented using multi-dimensional arrays. Needless to say that these operations are very often used in fields such as scientific computing, data analysis, and linear algebra.

  • Image Processing: Java applications that deal with image processing often utilize multi-dimensional arrays. Images can be represented as three-dimensional arrays. In this regard, each element represents a pixel with color information. Image manipulation operations like filtering, edge detection, resizing, and enhancement can be implemented using multi-dimensional arrays.

  • Game Development: Multi-dimensional arrays are widely used in Java game development. Game boards, maps, and terrain can be represented using multi-dimensional arrays. In this regard, each element corresponds to a specific location in the game world. Arrays can also store information. This may include game entities, terrain attributes, collision detection, and pathfinding data.

  • Data Storage and Analysis: Multi-dimensional arrays are employed for storing and analyzing large datasets in Java. For instance, in data science and machine learning applications, multi-dimensional arrays can store features and samples. Various algorithms and statistical operations can then be applied to these arrays. This is done for data analysis and modeling purposes.

  • Graphics and GUI Applications: Multi-dimensional arrays are employed in Java graphics and GUI applications. Arrays can store pixel or color information for rendering images on the screen. They can also be used to represent graphical objects. Furthermore, they can handle user interaction by storing information about their positions, states, and attributes.

Syntax of Multidimensional Array in Java Program

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:

  • dataType: This represents the data type of the elements stored in the array. It can be any valid data type in Java, such as int, double, char, String, or even custom class objects.

  • arrayName: This is the name you choose for your array variable. You can give it any valid identifier name according to Java naming conventions.

  • rows: This specifies the number of rows in the multidimensional array, representing the first dimension.

  • columns: This specifies the number of columns in the multidimensional array, representing the second dimension.

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.

Types of Multidimensional Arrays in Java

Multidimensional Array of Primitive Types

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
    }
}

Multidimensional Array of Objects

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
    }
}

Multidimensional Array of Arrays

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
    }
}

Multidimensional Array of Custom Objects

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
    }
}

Multidimensional Array in Java Example

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.

Conclusion

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. 

FAQs

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. 

Leave a Reply

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