Here's a Java program to rotate an array by K positions:
public class ArrayRotation {
public static void rotateArray(int[] arr, int k) {
int n = arr.length;
// To handle negative rotations
k = k % n;
if (k < 0) {
k += n;
}
reverseArray(arr, 0, n - 1); // Reverse the entire array
reverseArray(arr, 0, k - 1); // Reverse the first part up to k
reverseArray(arr, k, n - 1); // Reverse the remaining part after k
}
public static void reverseArray(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2;
System.out.println("Original array:");
printArray(arr);
rotateArray(arr, k);
System.out.println("Array after rotating by " + k + " positions:");
printArray(arr);
}
}
```
This program defines a method `rotateArray` that takes an array of integers `arr` and an integer `k` as input and rotates the array by `k` positions to the right. It first reverses the entire array, then reverses the first part up to `k`, and finally reverses the remaining part after `k`.
The `reverseArray` method is a helper method used to reverse a portion of the array specified by the start and end indices.
In the `main` method, an example array is initialized, rotated by `k` positions, and then printed before and after rotation.