Java Integer.rotateRight() – Examples

In this tutorial, we will learn about Java Integer.rotateRight() method, and learn how to use this method to rotate given integer bits in the right direction by given distance, with the help of examples.

rotateRight(int i, int distance)

Integer.rotateRight(i, distance) returns the value obtained by rotating the two’s complement binary representation of the specified int value i right by the specified number of bits distance.

Syntax

The syntax of rotateRight() method with the integer and distance is

</>
Copy
Integer.rotateRight(int i, int distance)

where

ParameterDescription
iThe integer value to be rotated.
distanceThe number of bit positions the given integer has to be rotated.

Returns

The method returns value of type int.

Example 1 – rotateRight(i, distance)

In this example, we will take an integer 1234, and rotate it right by a distance of 3.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		int i = 1234;
		int distance = 3;
		int result = Integer.rotateRight(i, distance);
		System.out.println("Result of rotateRight("+i+", "+distance+") = " + result);
	}
}

Output

Result of rotateRight(1234, 3) = 1073741978

Example 2 – rotateRight(i, distance) – Negative Distance

Giving negative distance to rotateLeft() would be rotating left.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		int i = 1234;
		int distance = -3;
		int result = Integer.rotateRight(i, distance);
		System.out.println("Result of rotateRight("+i+", "+distance+") = " + result);
	}
}

Output

Result of rotateRight(1234, -3) = 9872

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Integer.rotateRight() method, and also how to use this method with the help of Java example programs.