×

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by 90 degrees in Java. The anti-clockwise rotations of the matrix is also referred as the left rotation of a matrix, while the clockwise rotation is indeed referred to as the right rotation of that same matrix.

What is a Matrix in Java?

Technically referring, a matrix is a rectangular, two-dimensional array that contains either integers, symbols, or statements as its fundamental elements. The elements in the matrix are arranged in rows and columns.

For an instance, m x n matrix refers to a matrix containing 'm' number of rows and 'n' number of columns. 'a [i][j]', which denotes that the element an is represented in the i-th row and j-th column, can be used to represent individual values in the matrix, which are referred to as elements.

Look at the example below to understand how a matrix actually looks like

Example:

                              a[][]= { 12, 5, 0,

                                    11, 7, 6,

                                    10, 8, 15}

The above example is a matrix or it can also be termed as two-dimensional array, with 3 rows and 3 columns. The representation of the above matrix elements in Z form shall certainly include the entire first row of the matrix, the right diagonal and the entire last row of the matrix too.

Now let us discuss about how to rotate a given matrix by 90 degrees in clockwise direction and also in anti-clockwise direction.

Let us first look at how a matrix can be rotated in clockwise rotation or simply right rotation.

Rotating matrix 90 degrees in clockwise direction.

Rotating a matrix 90 degrees in clockwise direction is process which can be accomplished by implementing two steps. The two steps are:

  • Initially, determine the matrix's transpose.
  • Unless the matrix is 3x3, swap the entries in the initial column with those in the last column. The second column does not change.

Note: The number of columns and rows in a matrix must and should be same. Then only the rotation of any matrix in any direction would be possible.

Look at the example below to understand how the rotation works.

{[1 ,2 ,3]

  [4 ,5 ,6]

  [7 ,8 ,9]}

Let us find the transpose of the above matrix.

{[1 ,4 ,7]

[2 ,5 ,8]

[3 ,6 ,9]}

Now lets us swap the first column and the last column.

{[7 ,4 ,1]

[8 ,5 ,2]

[9 ,6 ,3]}

The above matrix after rotating 90 degrees in clockwise direction. Lets us go through a simple example program.

File name: Clockwise.java

public class Clockwise  
{  
//method to rotate the matrix 90 degrees in clockwise direction  
static void rotateRight(int matrix[][],int n)  
{  
//to find out the transpose of the matrix  
for(int i=0;i<n;i++)  
{  
for(int j=i;j<n;j++)  
{  
int temp = matrix[i][j];  
matrix[i][j] = matrix[j][i];  
matrix[j][i] = temp;  
}  
}  
  
//reversing the elements of each row 
for(int i=0;i<n;i++)  
{      
int low = 0, high = n-1;  
while(low < high)  
{  
int temp = matrix[i][low];  
matrix[i][low] = matrix[i][high];  
matrix[i][high] = temp;  
low++;  
high--;  
}  
}  
  
System.out.println("The matrix after rotating 90 degrees in clockwise direction: ");    
for(int i=0;i<3;i++)  
{  
for(int j=0;j<3;j++)  
{  
System.out.print(matrix[i][j]+" " +"\t");  
}  
System.out.println();  
}  
}
public static void main(String args[])  
{  
int n=3;  
// creating a matrix
int matrix[][] = new int[][]{ {1,2,3}, {4,5,6} , {7,8,9} };  
System.out.println("The matrix before rotating 90 degrees in clockwise direction: ");  
// displays the matrix
for(int i=0;i<3;i++)  
{  
for(int j=0;j<3;j++)  
{  
//displays the elements of the matrix     
System.out.print(matrix[i][j]+" " +"\t");  
}  
System.out.println();  
}  
//invoking the method
rotateRight(matrix, n);  
}  
}   

Output

The matrix before rotating 90 degrees in clockwise direction:
1       2       3
4       5       6
7       8       9
The matrix after rotating 90 degrees in clockwise direction:
7       4       1
8       5       2
9       6       3

Rotating matrix 90 degrees in anti-clockwise direction

File name: Anticlockwise.java

public class Anticlockwise
{  
//method to rotate the matrix 90 degrees in anti-clockwise direction  
static void rotateLeft(int matrix[][], int n)  
{  
//finding the transpose of the matrix
for(int i=0;i<n;i++)  
{  
for(int j=i;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++)  
{   
int low = 0;  
int high = n-1;  
while(low < high)  
{  
int temp = matrix[low][i];  
matrix[low][i] = matrix[high][i];  
matrix[high][i] = temp;  
low++;  
high--;  
}  
}  
//displays the matrix after the rotation   
System.out.println("The matrix after rotating in in anti-clockwise direction: ");  
for(int i=0;i<3;i++)  
{  
for(int j=0;j<3;j++)  
{  
System.out.print(matrix[i][j]+" "+"\t");  
}  
System.out.println();  
}  
}  
public static void main(String args[])  
{    
int n=3;  
//creating a matrix 
int matrix[][] = new int[][]{ {1,2,3}, {4,5,6} , {7,8,9} };  
//displays the matrix  
System.out.println("The matrix before rotating 90 degrees in anti-clockwise direction: ");  
for(int i=0;i<3;i++)  
{
for(int j=0;j<3;j++)  
{  
//displays elements of the matrix       
System.out.print(matrix[i][j]+" "+"\t");  
}  
System.out.println();  
}     
rotateLeft(matrix,n);  
}  
}  

Output:

The matrix before rotating 90 degrees in anti-clockwise direction:
1       2       3
4       5       6
7       8       9
The matrix after rotating in in anti-clockwise direction:
3       6       9
2       5       8
1       4       7

Related Topics

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.