Rotate matrix 90 degrees clockwise
Yes there is a better way to do it. It makes the computation really simple and elegant.

If you take the transpose of the matrix and then rotate the matrix row-wise along the mid row, you can get the same result as rotating the matrix by 90 degrees counter clock-wise.

For example:

[1 2 3] 
[4 5 6] 
[7 8 9]


Step 1: take its transpose:

[1 4 7]
[2 5 8]
[3 6 9]


Step 2: rotate the matrix across mid row:

[3 6 9]
[2 5 8]
[1 4 7]


This is exactly what you get when you rotate the matrix by 90 degrees left.

Here is the code:

public static void rotateMatrix(int[][] matrix){
    if(matrix == null)
        return;
    if(matrix.length != matrix[0].length)//INVALID INPUT
        return;
    getTranspose(matrix);
    rorateAlongMidRow(matrix);      
}

private static void getTranspose(int[][] matrix) {
    for(int i = 0; i &lt; matrix.length; i++){
        for(int j = i+1; j &lt; matrix.length ; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
}

private static void rorateAlongMidRow(int[][] matrix) {
    int len = matrix.length ;
    for(int i = 0; i &lt; len/2; i++){
        for(int j = 0;j &lt; len; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[len-1 -i][j];
            matrix[len -1 -i][j] = temp;
        }
    }
}


Edit: As suggested in the comment, for making it rotate clock-wise, just change the function getTranspose() to rotateAlongDiagonal() in rotateMatrix() function.

private static void rotateAlongDiagonal(int[][] matrix) {
    int len = matrix.length;
    for(int i = 0; i &lt; len; i++){
        for(int j = 0; j &lt; len - 1 - i ; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[len -1 - j][len-1-i];
            matrix[len -1 - j][len-1-i] = temp;
        }
    }
}