Multi-Dimensional Array in Java

Multi-Dimensional Array in Java

Multi-dimensional arrays in Java are arrays of arrays. The most commonly used multi-dimensional array is the two-dimensional array, which can be thought of as a table (or matrix) with rows and columns.

1. Declaration:

dataType[][] arrayName; 

2. Initialization:

You can initialize it at the time of declaration:

int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 

Or you can declare first and then initialize:

int[][] matrix; matrix = new int[3][3]; 

3. Accessing Elements:

To access elements, you'll need to specify two indices:

int x = matrix[0][1]; // x would be 2 

4. Iterating Through a Multi-dimensional Array:

Use nested loops:

for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } 

5. Irregular Multi-dimensional Arrays (Jagged Arrays):

Not all rows need to have the same number of columns:

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

Tutorial Example:

Let's put this all together in an example.

Create a Program to Implement Matrix Addition:

public class MatrixAddition { public static void main(String[] args) { int[][] matrixA = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] matrixB = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int[][] result = new int[3][3]; // Perform the addition: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { result[i][j] = matrixA[i][j] + matrixB[i][j]; } } // Display the result: System.out.println("Resultant Matrix:"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(result[i][j] + " "); } System.out.println(); } } } 

The output will be:

Resultant Matrix: 10 10 10 10 10 10 10 10 10 

This example showed how to use a two-dimensional array to perform matrix addition in Java. Similarly, other matrix operations can be performed by adapting the logic accordingly.


More Tags

filereader node-webkit cakephp-3.x normal-distribution angularfire onsubmit jsse datacontext updates vagrant

More Programming Guides

Other Guides

More Programming Examples