If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, a multidimensional array is an array of arrays, where each element of the array can be another array. This allows you to create arrays with multiple dimensions, such as 2D arrays (arrays with rows and columns), 3D arrays (arrays with rows, columns, and depth), and so on. Multidimensional arrays are useful when you need to represent tabular data or store information in a matrix-like structure.
The syntax to declare and create a multidimensional array in Java is as follows:
javaCopy codedataType[][] arrayName = new dataType[rows][columns];
Here, dataType
represents the data type of the elements in the array, arrayName
is the name of the array variable, rows
is the number of rows in the array, and columns
is the number of columns in each row. The rows
and columns
can be any positive integer.
Here's an example of a 2D array in Java:
javaCopy codepublic class TwoDimensionalArrayExample {
public static void main(String[] args) {
// Declare and create a 2D array of integers with 3 rows and 4 columns
int[][] matrix = new int[3][4];
// Assign values to the elements of the 2D array
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;
matrix[1][0] = 5;
matrix[1][1] = 6;
matrix[1][2] = 7;
matrix[1][3] = 8;
matrix[2][0] = 9;
matrix[2][1] = 10;
matrix[2][2] = 11;
matrix[2][3] = 12;
// Access and print the elements of the 2D array
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();
}
}
}
Output:
Copy code1 2 3 4 5 6 7 8 9 10 11 12
In the example above, we declare and create a 2D array named matrix
with 3 rows and 4 columns. We then assign values to each element of the array using double square brackets notation (e.g., matrix[0][0]
, matrix[0][1]
, etc.). Finally, we use nested loops to access and print the elements of the 2D array in a tabular format.
Similarly, you can create 3D arrays, 4D arrays, and so on by adding more dimensions to the array declaration and initialization. Multidimensional arrays are a powerful tool to represent complex data structures and solve various problems involving multiple dimensions of data.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0