0
0
JavaProgramBeginner · 2 min read

Java Program to Transpose Matrix with Output and Explanation

To transpose a matrix in Java, create a new matrix and use nested for loops to assign transposed[i][j] = original[j][i], then print the transposed matrix.
📋

Examples

Input[[1, 2], [3, 4]]
Output[[1, 3], [2, 4]]
Input[[5, 6, 7], [8, 9, 10]]
Output[[5, 8], [6, 9], [7, 10]]
Input[[1]]
Output[[1]]
🧠

How to Think About It

To transpose a matrix, think of swapping rows and columns. The element at row i and column j in the original matrix becomes the element at row j and column i in the new matrix. So, you create a new matrix with swapped dimensions and copy elements accordingly.
📐

Algorithm

1
Get the number of rows and columns of the original matrix.
2
Create a new matrix with rows and columns swapped.
3
Use nested loops to go through each element of the original matrix.
4
Assign the element at position (i, j) in the original matrix to position (j, i) in the new matrix.
5
Print the new transposed matrix.
💻

Code

java
public class TransposeMatrix {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2}, {3, 4}};
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] transpose = new int[cols][rows];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                transpose[j][i] = matrix[i][j];
            }
        }

        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                System.out.print(transpose[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output
1 3 2 4
🔍

Dry Run

Let's trace the matrix [[1, 2], [3, 4]] through the code

1

Initialize matrix and dimensions

matrix = [[1, 2], [3, 4]], rows = 2, cols = 2, transpose = new int[2][2]

2

First outer loop i=0

Inner loop j=0: transpose[0][0] = matrix[0][0] = 1 Inner loop j=1: transpose[1][0] = matrix[0][1] = 2

3

Second outer loop i=1

Inner loop j=0: transpose[0][1] = matrix[1][0] = 3 Inner loop j=1: transpose[1][1] = matrix[1][1] = 4

4

Print transpose matrix

Print row 0: 1 3 Print row 1: 2 4

transpose[j][i]Value assigned
transpose[0][0]1
transpose[1][0]2
transpose[0][1]3
transpose[1][1]4
💡

Why This Works

Step 1: Create transpose matrix

We create a new matrix with swapped dimensions because the number of rows becomes the number of columns and vice versa in the transpose.

Step 2: Copy elements with swapped indices

Each element at position (i, j) in the original matrix is copied to position (j, i) in the transpose matrix to swap rows and columns.

Step 3: Print the transposed matrix

We print the new matrix row by row to show the transposed result clearly.

🔄

Alternative Approaches

In-place transpose for square matrix
java
public class TransposeMatrix {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2}, {3, 4}};
        int n = matrix.length;

        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
This method modifies the original matrix directly but works only for square matrices.
Using streams (Java 8+)
java
import java.util.Arrays;

public class TransposeMatrix {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2}, {3, 4}};
        int rows = matrix.length;
        int cols = matrix[0].length;

        int[][] transpose = new int[cols][rows];

        for (int i = 0; i < cols; i++) {
            final int col = i;
            transpose[i] = Arrays.stream(matrix).mapToInt(row -> row[col]).toArray();
        }

        for (int[] row : transpose) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
This approach uses Java streams for a concise transpose but may be less clear for beginners.

Complexity: O(rows * cols) time, O(rows * cols) space

Time Complexity

The program uses nested loops to visit each element once, so it runs in O(rows * cols) time.

Space Complexity

A new matrix of size cols x rows is created, so space complexity is O(rows * cols).

Which Approach is Fastest?

In-place transpose is fastest for square matrices as it uses no extra space, but for non-square matrices, creating a new matrix is necessary.

ApproachTimeSpaceBest For
New matrix with nested loopsO(rows * cols)O(rows * cols)All matrices, simple and clear
In-place transposeO(n^2)O(1)Square matrices only, memory efficient
Streams approachO(rows * cols)O(rows * cols)Concise code, Java 8+
💡
Always check matrix dimensions before transposing to avoid index errors.
⚠️
Beginners often forget to swap row and column indices, causing incorrect transpose results.