Here’s a Java program to rotate an array by a given number of positions:
import java.util.Arrays; import java.util.Scanner; public class ArrayRotation { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of positions to rotate the array: "); int k = scanner.nextInt(); rotateArray(arr, k); System.out.println("Rotated array: " + Arrays.toString(arr)); } public static void rotateArray(int[] arr, int k) { int n = arr.length; int[] temp = new int[k]; for (int i = 0; i < k; i++) { temp[i] = arr[i]; } for (int i = k; i < n; i++) { arr[i - k] = arr[i]; } for (int i = 0; i < k; i++) { arr[n - k + i] = temp[i]; } } }
In this program, we first create an integer array and take user input for the number of positions to rotate the array. We then call the `rotateArray()` method to rotate the array.
The `rotateArray()` method takes an integer array `arr` and an integer `k` as parameters and rotates the array by `k` positions. We first create a temporary array `temp` of size `k` and copy the first `k` elements of `arr` to `temp` using a for loop. We then use another for loop to shift the remaining elements of `arr` to the left by `k` positions. We then use a third for loop to copy the elements of `temp` to the end of `arr` to complete the rotation.
At the end of the program, we print out the rotated array using the `Arrays.toString()` method.