Multi-dimensional array in Java (Java 2D array & Java 3D array)

 Java programming relies heavily on arrays to efficiently store and access multiple elements of the same data type. However, there are instances where data requires more than one dimension to be effectively organized. Multi-dimensional arrays are the solution to this problem. 

This comprehensive article will delve into multi-dimensional arrays, focusing on Java 2D (two-dimensional) arrays and Java 3D (Three dimensional) arrays. We will explore their concept, uses, and various functionalities.

Multi-dimensional array in Java

An array with more than one dimension is called a multi-dimensional array in Java. It is an array of arrays. In this type of array, each index of a multi-dimensional array further contains an array.  Java 2D (Two-dimensional) and Java 3D (three-dimensional) arrays are the two most important examples of multi-dimensional arrays. Let us understand the concept of Java multi-dimensional array with the help of a 2D array. 

Java 2D (Two Dimensional) Array 

In Java, a 2D array is one of the simplest forms of a multi-dimensional array. This structure arranges data in a matrix-like format consisting of rows and columns, much like an Excel file. To access an element in the 2D array, one must use both the row and column indexes.

Declaring and initializing a Java 2D (two-Dimensional) Array:

To declare a 2D array, we use square brackets for the dimensions. For example, int[][] matrix; declares a 2D integer array. To initialize it, we specify the size of each dimension and allocate memory accordingly. For instance, int[][] matrix = new int[3][4];. This statement creates a 2D array with three rows and four columns.

Syntax to Declare a Two-dimensional Array in Java

dataType[][] arrayRefVar; 

    or

dataType [][]arrayRefVar; 

    or

dataType arrayRefVar[][]; 

    or

dataType []arrayRefVar[];   

Once a 2D array is declared, it is instantiated with the help of new keyword.

int[][] myArr;

myArr=new int[row][columns];

It can also be written as:

int[][] myArr = new int[row][columns];

For example,

int[][] myArr = new int[3][3]; //3 row and 3 column  

This code snippet will create a 2D array with three rows and three columns as shown below.

java 2d array

To initialize a 2D array, we must specify the row and column indexes. For example, the above 2D array can be initialized as follow:


myArr[0][0]=10;  
myArr[0][1]=20;  
myArr[0][2]=30;  
myArr[1][0]=40;  
myArr[1][1]=50;  
myArr[1][2]=60;  
myArr[2][0]=70;  
myArr[2][1]=80;  
myArr[2][2]=90;  

Explanation:

A 2D array named myArr is initialized in the given code with three rows and three columns. The specific values 1 to 9 are assigned to their elements using their respective row and column indices. The resulting 2D array represents a matrix with the following elements: 1 2 3 in the first row, 4 5 6 in the second row, and 7 8 9 in the third row. Each element can be accessed using its corresponding row and column index, for instance, myArr[0][0] refers to 1, and myArr[2][2] refers to 9.

 

Column1

Column2

Column3

Row1

10

20

30

Row2

40

50

60

Row3

70

80

90

We can also declare and initialize a two-dimensional array in Java like this:

int[][] myArr = {
                              {10, 20, 30},
                              {40, 50, 60},
                              {70, 80, 90}
};

The above code snippet will create and initialize an array similar to the previous one. Note, we don’t have to give row and column sizes this way.

Accessing (Printing) Elements in Java 2D Arrays:

Printing elements in a 2D array involves two indices: one for the row and one for the column. For example, int value = matrix[1][2]; retrieves the element at the second row and third column. We can traverse the entire array using nested loops, which help perform operations on each element.

In the following simple example, I will teach you how to declare, instantiate, initialize, and print the 2Dimensional array using a simple for loop in Java.

Program: TwoDimensionalArrayUsingFor.java 

class TwoDimensionalArrayUsingFor{  

public static void main(String args[]){  

    //declaring and initializing 2D array  

    int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  

    //printing 2D array  

    for(int i=0;i<3;i++){  

           for(int j=0;j<3;j++){  

           System.out.print(arr[i][j]+" ");  

    }  

    System.out.println();  

    } 

   }

}  

The output will be:       

       1 2 3

       2 4 5

       4 4 5

Explanation:

The Java code declares and initializes a 2D array arr with three rows and three columns. The array is filled with integer values: 1 2 3 in the first row, 2 4 5 in the second row, and 4 4 5 in the third row. The nested for loop is used to iterate through the array and print its elements row by row. The output will display the contents of the 2D array in the form of a matrix. Outer for loop will access the row indices, while the inner loop will iterate through the column indices.

Program: TwoDimensionalArrayUsingForeach.java 

We can also access and print Java 2D array elements using enhanced or for each loop.

class TwoDimensionalArrayUsingForeach {

    public static void main(String args[]) {

        // declaring and initializing 2D array

        int arr[][] = { { 1, 2, 3 }, { 2, 4, 5 }, { 4, 4, 5 } };

 

        // printing 2D array using foreach loop

        for (int[] row : arr) {

            for (int element : row) {

                System.out.print(element + " ");

            }

            System.out.println();

        }

    }

}

The output will be:       

       1 2 3

       2 4 5

       4 4 5

Explanation:

In this Java program, a 2D array named as arr is declared and initialized with integer values. The outer foreach loop iterates over each row of the 2D array. Each iteration extracts a single row and assigns it to the variable row. Then, the inner foreach loop iterates over the elements within the current row. Each iteration extracts a single element and assigns it to the variable element.

Jagged Arrays:

A jagged array is an array of arrays where each row can have a different number of elements. Unlike a regular 2D array, jagged arrays are flexible and useful when the data is not uniformly distributed. To create a jagged array, we declare and initialize the rows separately. For instance,

 

int[][] jaggedArray = new int[3][]; // Column size is not specified here because it varies in each row

jaggedArray[0] = new int[2];

jaggedArray[1] = new int[4];

jaggedArray[2] = new int[3];

This can be visualized as below:

2 Locations

 

 

 

 

4 Locations

 

 

 

 

3 Locations

 

 

 

 

 

Explanation:

In this code snippet, we create a jagged 2D array called jaggedArray. A jagged array is an array of arrays, where each sub-array can have a different number of elements. In this case, we initialize jaggedArray as a 3x0 2D array. This means that jaggedArray has three rows, but each row has a different number of columns.

The first row is initialized with two elements, the second row with four elements, and the third row with three elements. The jagged array allows for flexibility in the size of each row, enabling efficient memory utilization when the number of elements varies across rows. This construct is useful when dealing with irregular data or when data size is flexible for all elements.

Declaring and initializing a 2D jagged array in Java:

int[][] jaggedArray = new int[3][];

jaggedArray[0] = new int[]{10, 20};

jaggedArray[1] = new int[]{40, 50, 60, 100};

jaggedArray[2] = new int[]{70, 80, 90};

This can also be done as follow:

int[][] jaggedArray = {

                              {10, 20},

                              {40, 50, 60, 100},

                              {70, 80, 90}

          };

 

This can be visualized like this:

 

jaggedArray[0]

10

20

 

 

jaggedArray[1]

40

50

60

100

jaggedArray[2]

70

80

90

 

 

Program: JaggedArrayExample.java 

Here's an illustration to initialize and print elements of a jagged array:

public class JaggedArrayExample {

    public static void main(String[] args) {

        int[][] jaggedArray = new int[3][];

        jaggedArray[0] = new int[] {1, 2};

        jaggedArray[1] = new int[] {3, 4, 5, 6};

        jaggedArray[2] = new int[] {7, 8, 9};

 

        // Printing all elements of the jagged array using for loops

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

            for (int j = 0; j < jaggedArray[i].length; j++) {

                System.out.print(jaggedArray[i][j] + " ");

            }

            System.out.println();

        }

    }

}

The output of above program will be:

1 2

3 4 5 6

7 8 9

Explanation:

In this example, a 2D jagged array named jaggedArray is declared with three rows. The first row contains elements 1 and 2, the second row contains elements 3, 4, 5, and 6, and the third row contains elements 7, 8, and 9.

The code uses nested for loops to iterate over each row and its elements. The outer loop goes through each row, and the inner loop iterates through the elements within that row. During each iteration, the elements are printed to the console, and a new line is added after printing all elements of a row, resulting in the complete representation of the jagged array's elements being displayed.

Java 3D (Three dimensional) Array:

A Java 3D array extends a Java 2D array, allowing data to be organized in three dimensions: rows, columns, and depth. It can be thought of as a collection of 2D arrays, forming a cube-like structure. In Java, a 3D array is declared and initialized using the following syntax:

dataType[][][] arrayName = new dataType[depth][rows][columns];

Here, dataType represents the data type of the elements stored in the 3D array, and arrayName is the name of the array. The depth, rows, and columns represent the size of the 3D array in the respective dimensions.

Creating and Accessing Elements in a 3D Array:

To create a 3D array, you can use nested loops to traverse the elements. Accessing an element in a 3D array requires three indices: one for each dimension. For example, array[depthIndex][rowIndex][colIndex] retrieves the element at the specified position.

int[][][] threeDArray = new int[2][3][2];

Accessing and initializing the above array,

threeDArray [0][0][0] = 10;

threeDArray [0][0][1] = 20;

threeDArray [0][1][0] = 30;

threeDArray [0][1][1] = 40;

threeDArray [0][2][0] = 50;

threeDArray [0][2][1] = 60;

threeDArray [1][0][0] = 70;

threeDArray [1][0][1] = 80;

threeDArray [1][1][0] = 90;

threeDArray [1][1][1] = 10;

threeDArray [1][2][0] = 20;

threeDArray [1][2][1] = 30;

We can also declare and initialize in a single line,

int[][][] threeDArray = {

                                             {

     {10,20},

     {30,40},

     {50,60}

 },

 {

    {70,80},

   {90,10},

   {20,30}

}

  };

The above concept can be visualized as follow:

Java 3d array

Program: Initializing and Accessing Elements in a 3D Array:

public class ThreeDimensionalArrayExample {

    public static void main(String[] args) {

        int[][][] threeDArray = {

            {

                {1, 2, 3},

                {4, 5, 6},

                {7, 8, 9}

            },

            {

                {10, 11, 12},

                {13, 14, 15},

                {16, 17, 18}

            }

 };

        // Accessing elements in the 3D array

       // Retrieves the element at depth 1, row 2, and column 0 (16)

        int value = threeDArray[1][2][0];

        System.out.println("Value at threeDArray[1][2][0]: " + value);

    }

}

Output:
Value at threeDArray[1][2][0]: 16

Explanation:

We have declared and initialized a 3D array named threeDArray in this Java program. It consists of two 2D arrays, forming a cube-like structure with dimensions of 2x3x3. The first 2D array contains the values 1 to 9, arranged in rows and columns, and the second 2D array similarly contains the values 10 to 18.

To access elements in the 3D array, we use three indices - the first index represents the depth, the second index represents the row, and the third index represents the column. For example, threeDArray[1][2][0] refers to the element at depth 1, row 2, and column 0, which is 16. The program prints the value 16 with the message "Value at threeDArray[1][2][0]: 16" to demonstrate how to access elements in a 3D array. 3D arrays provide a powerful way to organize and manipulate data in three dimensions, which can be useful in applications involving volumetric data, 3D graphics, and simulations.

Program: Initializing and Traversing a 3D Array:

public class ThreeDimensionalArrayTraversal {

    public static void main(String[] args) {

        int[][][] threeDArray = new int[2][3][4];

 

        // Initializing elements in the 3D array

        for (int depth = 0; depth < 2; depth++) {

            for (int row = 0; row < 3; row++) {

                for (int col = 0; col < 4; col++) {

                    threeDArray[depth][row][col] = depth + row + col;

                }

            }

        }

        // Traversing and printing the 3D array

        for (int depth = 0; depth < 2; depth++) {

            for (int row = 0; row < 3; row++) {

                for (int col = 0; col < 4; col++) {

                    System.out.print(threeDArray[depth][row][col] + " ");

                }

                System.out.println();

            }

            System.out.println();

        }

    }

}

Output:

0 1 2 3

1 2 3 4

2 3 4 5

 

1 2 3 4

2 3 4 5

3 4 5 6 

Explanation:

In this Java program, we have declared a 3D array named `threeDArray` with dimensions 2x3x4. It is created using the `new` keyword, and all elements are initialized to 0 by default. The program then utilizes nested `for` loops to iterate through the 3D array. The outermost loop (`depth`) iterates over the depth of the 3D array (2 in this case). The next two loops (`row` and `col`) traverse the rows and columns of each 2D array within the 3D array.

During the initialization phase, each element in the 3D array is assigned a value equal to the sum of its depth, row, and column indices. Finally, the program prints the contents of the 3D array, displaying the elements row by row for each depth. The output will show the values 0 to 9, organized in two 3x4 2D arrays. This example demonstrates how to initialize and traverse a 3D array, making it useful for scenarios involving complex three-dimensional data structures and applications such as 3D modeling and simulations.

Everyday Use Cases of Multi-Dimensional Arrays:

Multi-dimensional arrays find various applications in programming. They are ideal for representing matrices in mathematical computations, grids, tables, and game boards. For example, Sudoku can be efficiently expressed using a 2D array.

Methods and Functions for Multi-Dimensional Arrays:

Java provides valuable methods for multi-dimensional arrays. For instance, to find the dimensions of an array, we can use array.length for the rows and array[i].length for the columns in a jagged array. Additionally, we can create functions to search for elements or transpose the array. Here's an example of a function that calculates the sum of elements in a 2D array:

public class SumOfElementsExample {

    public static int sumOfElements(int[][] matrix) {

        int sum = 0;

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

            for (int j = 0; j < matrix[i].length; j++) {

                sum += matrix[i][j];

            }

        }

        return sum;

    }

 

    public static void main(String[] args) {

        int[][] matrix = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };

 

        int totalSum = sumOfElements(matrix);

        System.out.println("Sum of elements in the 2D array: " + totalSum);

    }

}

The output of above program will be:

Sum of elements in the 2D array: 45

Explanation:

In this Java code, we have a method called sumOfElements that takes a 2D array (matrix) as input and calculates the sum of all its elements. It uses nested loops to traverse through the rows and columns of the matrix and accumulates the values in the variable sum. 

The primary method initializes a 3x3 matrix with specific values, then calls the sumOfElements method to compute the total sum. The output will display the result as "Sum of elements in the 2D array: 45", the sum of all elements in the given matrix. This code demonstrates how to efficiently calculate the sum of elements in a 2D array.

Memory Management and Performance Considerations:

While multi-dimensional arrays are powerful, they consume more memory than single-dimensional arrays. Therefore, it's crucial to be mindful of memory management, especially when dealing with large arrays. Additionally, nested loops used to traverse multi-dimensional arrays can impact performance, so optimizing the code becomes essential

Java Practice Programs

Program 1: Find the Maximum Element in a 2D Array Problem Statement: 

Problem Statement: Given a 2D array, write a Java program to find and print the maximum element in the array.

Solution:

public class MaxElementIn2DArray {

    public static void main(String[] args) {

        int[][] matrix = {

            {5, 10, 3},

            {8, 2, 15},

            {7, 12, 9}

        };

 

        int maxElement = matrix[0][0];

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

            for (int j = 0; j < matrix[i].length; j++) {

                if (matrix[i][j] > maxElement) {

                    maxElement = matrix[i][j];

                }

            }

        }

 

        System.out.println("Maximum element in the 2D array: " + maxElement);

    }

}

Output of above program:

Maximum element in the 2D array: 15

 Program 2: Transpose a Square Matrix

Problem Statement: Given a square matrix (n x n) in a 2D array, write a Java program to transpose the matrix in place (without additional memory) and print the resulting transposed matrix.

 

public class TransposeSquareMatrix {

    public static void main(String[] args) {

        int n = 3; // Square matrix size (n x n)

        int[][] matrix = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };

 

        // Transpose the matrix in-place

        for (int i = 0; i < n; i++) {

            for (int j = i + 1; j < n; j++) {

                // Swap elements across the main diagonal

                int temp = matrix[i][j];

                matrix[i][j] = matrix[j][i];

                matrix[j][i] = temp;

            }

        }

 

        // Print the transposed matrix

        System.out.println("Transposed Matrix:");

        for (int i = 0; i < n; i++) {

            for (int j = 0; j < n; j++) {

                System.out.print(matrix[i][j] + " ");

            }

            System.out.println();

        }

    }

}

In this program, we define a square matrix of size 3x3 (which can be modified by changing the value of n). The for loops iterate through the matrix, and we swap elements across the main diagonal (from top-left to bottom-right) to achieve the transpose of the matrix in-place. Finally, we print the resulting transposed matrix. The output will display the transposed matrix as:

 

Transposed Matrix: 

1 4 7 

2 5 8 

3 6 9 

Program 3: Rotate a 2D Array

Problem Statement: Given a rectangular matrix (m x n) in the form of a 2D array, write a Java program to rotate the matrix 90 degrees clockwise. Print the rotated matrix.

Solution:

public class RotateRectangularMatrix {

    public static void main(String[] args) {

        int[][] matrix = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9},

            {10, 11, 12}

        };

        int rows = matrix.length;

        int columns = matrix[0].length;

 

        // Create a new matrix to store the rotated elements

        int[][] rotatedMatrix = new int[columns][rows];

 

        // Rotate the matrix 90 degrees clockwise

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < columns; j++) {

                rotatedMatrix[j][rows - 1 - i] = matrix[i][j];

            }

        }

        // Print the rotated matrix

        System.out.println("Rotated Matrix (90 degrees clockwise):");

        for (int i = 0; i < columns; i++) {

            for (int j = 0; j < rows; j++) {

                System.out.print(rotatedMatrix[i][j] + " ");

            }

            System.out.println();

        }

    }

}

In this program, we have a rectangular matrix of size 4x3 (which can be modified by changing the values of rows and columns). We create a new matrix rotatedMatrix to store the rotated elements. The nested for loops iterate through the original matrix, and we place the elements into the new matrix to achieve the 90 degrees clockwise rotation. Finally, we print the resulting rotated matrix. The output will display the rotated matrix as:

 

Rotated Matrix (90 degrees clockwise):

10 7 4 1 

11 8 5 2 

12 9 6 3 

 

FAQs:

1. What is a multi-dimensional array in Java?

A multi-dimensional array in Java is an array of arrays. It allows data to be organized in multiple dimensions, forming a grid-like structure. Unlike a one-dimensional array, which is a list of elements, a multi-dimensional array can have rows and columns, making it suitable for representing matrices, tables, and other complex data structures. 

2. How do I declare and initialize a multi-dimensional array in Java?

To declare and initialize a multi-dimensional array in Java, you can use the following syntax:

     dataType[][] arrayName = new dataType[rows][columns];

For example, `int[][] matrix = new int[3][4];` creates a 3x4 two-dimensional array called `matrix`.

3. Can I have multi-dimensional arrays with different sizes for each row?

Yes, you can create jagged arrays in Java, which are multi-dimensional arrays with different sizes for each row. For example, you can have a 2D array with rows having varying numbers of columns. This flexibility allows for more efficient memory utilization when dealing with irregular data structures.

4. How do I access elements in a multi-dimensional array?

To access elements in a multi-dimensional array, you need to use the indices corresponding to the row and column of the element you want to access. For example, `matrix[1][2]` refers to the element in the second row and third column of the `matrix` array.

5. What are the practical applications of multi-dimensional arrays in Java?

Multi-dimensional arrays in Java are widely used in various applications, such as storing and processing 2D data like images, representing matrices in mathematical operations, managing game boards in 2D games, and handling data in tables and spreadsheets. Additionally, they are essential for dealing with volumetric data and 3D graphics in applications that require three-dimensional representations.

Conclusion:

In this detailed article, we have discussed an array of arrays, i.e., multi-dimensional arrays in Java. We also discussed Java 2D arrays, Java jagged arrays, and Java 3D arrays. We learned how to declare and initialize these arrays with the help of various code examples and illustrations. 

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !