This Java code example demonstrates the use of multidimensional arrays, specifically focusing on a 2D array. It shows how to initialize, traverse, and transpose a matrix. The program illustrates fundamental operations, providing a clear understanding of working with two-dimensional data structures in Java.
public class MultidimensionalArrayExample {
public static void main(String[] args) {
// Initializing a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Displaying the 2D array
System.out.println("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();
}
// Transposing the 2D array
int[][] transposed = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transposed[j][i] = matrix[i][j];
}
}
// Displaying the transposed 2D array
System.out.println("\nTransposed 2D Array:");
for (int i = 0; i < transposed.length; i++) {
for (int j = 0; j < transposed[i].length; j++) {
System.out.print(transposed[i][j] + " ");
}
System.out.println();
}
}
}