0
0
JavaHow-ToBeginner · 3 min read

How to Rotate Matrix 90 Degrees in Java - Simple Guide

To rotate a matrix 90 degrees clockwise in Java, create a new matrix and set each element at position rotated[j][n - 1 - i] to the original element at matrix[i][j]. This shifts rows to columns in reverse order, effectively rotating the matrix.
📐

Syntax

To rotate a matrix 90 degrees clockwise, you use a nested loop to copy elements from the original matrix to a new matrix with swapped indices.

  • matrix[i][j]: element at row i and column j in the original matrix.
  • rotated[j][n - 1 - i]: position in the rotated matrix where the element is placed.
  • n: size of the matrix (number of rows or columns).
java
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        rotated[j][n - 1 - i] = matrix[i][j];
    }
}
💻

Example

This example shows how to rotate a 3x3 matrix 90 degrees clockwise and print the result.

java
public class RotateMatrix {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int n = matrix.length;
        int[][] rotated = new int[n][n];

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

        System.out.println("Original matrix:");
        printMatrix(matrix);
        System.out.println("\nRotated matrix 90 degrees clockwise:");
        printMatrix(rotated);
    }

    private static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Output
Original matrix: 1 2 3 4 5 6 7 8 9 Rotated matrix 90 degrees clockwise: 7 4 1 8 5 2 9 6 3
⚠️

Common Pitfalls

Common mistakes when rotating a matrix include:

  • Modifying the original matrix in place without a proper algorithm, which can overwrite needed values.
  • Mixing up the indices, such as using rotated[i][j] instead of rotated[j][n - 1 - i].
  • For non-square matrices, this method needs adjustment because the number of rows and columns differ.
java
/* Wrong way: overwriting original matrix without backup */
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        matrix[j][n - 1 - i] = matrix[i][j]; // Overwrites original data
    }
}

/* Right way: use a new matrix to store rotated values */
int[][] rotated = new int[n][n];
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        rotated[j][n - 1 - i] = matrix[i][j];
    }
}
📊

Quick Reference

To rotate a square matrix 90 degrees clockwise:

  • Create a new matrix of the same size.
  • Use nested loops to assign rotated[j][n - 1 - i] = matrix[i][j].
  • Print or use the rotated matrix as needed.
StepActionCode snippet
1Create new matrixint[][] rotated = new int[n][n];
2Loop through original matrixfor (int i = 0; i < n; i++) {...}
3Assign rotated valuesrotated[j][n - 1 - i] = matrix[i][j];
4Use rotated matrixprintMatrix(rotated);

Key Takeaways

Always use a new matrix to store rotated values to avoid overwriting original data.
Rotate by assigning element at (i, j) to (j, n - 1 - i) in the new matrix.
This method works only for square matrices; non-square matrices need different handling.
Use nested loops to iterate through all elements for rotation.
Print the rotated matrix to verify the result visually.