Learn how to create Java Multidimensional Arrays Program with examples.
A multidimensional array in Java stores data in rows and columns, making it ideal for representing matrices and tabular data.
Code Explanation (Step-by-Step)
• Create a Scanner class object to accept user input.
• Declare the size of the multidimensional array.
• Use the sc.nextInt() method to enter the number of rows and columns.
• Traverse the nested for loops based on the number of rows and columns.
• Enter the matrix elements and store them in the array using a[i][j].
• Traverse another set of nested for loops to display the matrix elements.
• Print the multidimensional array (matrix) in row and column format.
import java.util.Scanner;
public class MultidimensionalArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row, column;
int a[][] = new int[5][5];
System.out.println("Enter the number of rows :");
row = sc.nextInt();
System.out.println("Enter the number of columns :");
column = sc.nextInt();
System.out.println("Enter the elements to create Matrix :");
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
System.out.println("Now the Multidimensional Matrix is :");
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}
Output :-
Enter the number of rows :-
3
Enter the number of columns :-
4
Enter the elements to create Matrix :-
12
23
34
56
76
43
78
98
34
30
74
89
Now the Multidimensional Matrix is :-
12 23 34 56
76 43 78 98
34 30 74 89
What Are Java Multidimensional Arrays?
Java Multidimensional Arrays are arrays that contain one or more arrays as their elements. They are used to store data in a tabular format consisting of rows and columns. The most common type of multidimensional array is a two-dimensional (2D) array, which is often used to represent matrices, tables, and grids.
A multidimensional array is also known as an array of arrays because each element of the main array can hold another array.
int[][] a = new int[3][5];
In this example :`
- 3 represents the number of rows.
- 5 represents the number of columns.
- The array can store a total of 3 × 5 = 15 elements.
Declare the Array Structure
- 10 20 30 40
- 50 60 70 80
- 90 100 110 111
Explain Here:
- Row 0: 10 20 30 40
- Row 1: 50 60 70 80
- Row 2: 90 100 110 111
Here are some related Java 8 programs that will help you understand Stream API concepts better: