Integer rotateLeft() Method in Java
Bit shifting is a type of bitwise operation which is performed on all the bits of a binary value by moving the bits by a definite number of places towards left or right. Java has a single Logical left shift operator (<< ). When the value 0001(i.e., 1) is shifted left, it becomes 0010(i.e., 2) which on shifting again to the left becomes 0100 or 4. The same process is applied for the right shift operation.
The java.lang.Integer.rotateLeft() method is used to shift the bits of an Integer value, represented in its binary 2’s complementary form towards left by a specified number of bits. (Bits are shifted to the left or higher-order).
public static int rotateLeft(int value, int shifts)
Parameters: The method takes two parameters:
- a : This is of integer type and refers to the value on which operation is to be performed.
- shifts : This is also of integer type and refers to the distance of rotation.
Return Value: The method returns the value obtained by rotating the two’s complement binary representation of the specified int value towards left by the specified number of shift bits.
Input: 12 Output: 24 Explanation: Consider an integer a = 12 Binary Representation = 00001100 After 1 left shift it will become=00011000 So that is= 24
Below programs illustrate the java.lang.Integer.rotateLeft() method.
Program 1: For a positive number.
8 32 128 512 2048 8192
Program 2: For a negative number.
Program 3: For a decimal value and string.
Note: It returns an error message when a decimal value and string is passed as an argument
prog.java:9: error: incompatible types: possible lossy conversion from double to int int a = 15.71; ^ prog.java:18: error: incompatible types: String cannot be converted to int int b = "61"; ^ 2 errors
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.