Java Integer.rotateLeft() – Examples

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

rotateLeft(int i, int distance)

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

The rotation is circular, meaning, the bits that come out on the left side enter the right side.

Syntax

The syntax of rotateLeft() method with integer and distance as parameters is

</>
Copy
Integer.rotateLeft(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 static int.

Example 1 – rotateLeft(i, distance)

In this example, we will take an integer 1234, and rotate it left 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.rotateLeft(i, distance);
		System.out.println("Result of rotateLeft("+i+", "+distance+") = " + result);
	}
}

Output

Result of rotateLeft(1234, 3) = 9872

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

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

Java Program

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

Output

Result of rotateLeft(1234, -3) = 1073741978

Conclusion

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