Home >>Java Programs >Java Program to right rotate the elements of an array
In this example, we will create a java program to rotate the elements of array towards its right by the specified number of times. Any given array is said to be right rotated if all the elements of that array are moved to its right by one position. We can do this by looping through the array and shifting each element of the array to its next position. In this way the last element of the array will become the first element of the rotated array.
Program:
class Main
{
public static void main(String[] args)
{
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 4;
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
for(int i = 0; i < n; i++)
{
int j, last;
last = arr[arr.length-1];
for(j = arr.length-1; j > 0; j--)
{
arr[j] = arr[j-1];
}
arr[0] = last;
}
System.out.println();
System.out.println("Array after right rotation: ");
for(int i = 0; i< arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}