Java Multidimensional Arrays: Initialization, Traversal, and Transposition

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.

Code Example

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();
        }
    }
}

Explanation

  1. Initializing a 2D Array: Creates a 3×3 matrix with predefined values.
  2. Displaying the 2D Array: Uses nested loops to print each element.
  3. Transposing the Array: Switches rows and columns to create a new transposed matrix.
  4. Displaying the Transposed Array: Prints the elements of the transposed matrix.