Example 1 — Rotate Bits Right
Rotate a few values right and compare with an unsigned shift, in hex.
public class IntegerRotateRightDemo {
static String hex(int n) {
return String.format("%08x", n);
}
public static void main(String[] args) {
System.out.println("8 by 3: " + hex(Integer.rotateRight(8, 3)));
System.out.println("1 by 1: " + hex(Integer.rotateRight(1, 1)));
System.out.println("1 >>> 1: " + hex(1 >>> 1));
System.out.println("0x12345678 by 8: " + hex(Integer.rotateRight(0x12345678, 8)));
}
} How It Works
- A normal move. Rotating 8 right by 3 gives 1, the same as a shift, because no set bit falls off.
- Wrapping around. The single bit of 1 leaves on the right and comes back on the left, giving
80000000. - A shift loses it.
1 >>> 1throws the bit away and leaves00000000. - Whole bytes. Rotating right by 8 moves the low byte
78to the top:78123456.

