Shift Operators in JavaIn Java, shift operators are the special type of operators that work on the bits of the data. These operators are used to shift the bits of the numbers from left to right or right to left depending on the type of shift operator used. There are three types of shift operators in Java:
Note: Java does not support the unsigned left shift operator (<<< ).Signed Left Shift OperatorThe signed left shift operator is a special type of operator used to move the bits of the expression to the left according to the number specified after the operator. Let's understand some examples to understand the working of the left shift operator. Consider x =5. Binary equivalent of 5 is 0101. Assume that the statement is as follows: x<<4, let y be 4 Let's implement the above logic in a Java program. LeftShift.java Output: The value is: 80 Signed Right Shift OperatorThe signed right shift operator is a special type of operator used to move the bits of the expression to the right according to the number specified after the operator. Let's understand some examples to understand the working of the right shift operator. Consider x=80. Binary equivalent of 80 is 1010000. Assume that the statement is as follows: x>>4, let y be 4 Let's implement the above logic in a Java program. RightShift.java Output: The right shifted value is : 5 Unsigned Right Shift OperatorThe unsigned right shift operator is a special type of right shift operator that does not use the signal bit to fill in the sequence. The unsigned sign shift operator on the right always fills the sequence by 0. Let's take the same example of the right-shift operator to understand the concept of the left-shift operator. x => 40 => 0000 0000 0000 0000 0000 0000 0010 1000 A negative number is the 2's complement of its positive number. So, y => -40 => 1111 1111 1111 1111 1111 1111 1101 1000 Thus x >>> 2 = 0000 0000 0000 0000 0000 0000 0000 1010 And y >>> 2 = 0011 1111 1111 1111 1111 1111 1111 0110 UnshinedRightShift.java Output: The right sifted value of 40 by 5 is : 1 The right shifted value of -40 by 5 is : -2 Note : Unlike unsigned Right Shift, there is no "<<<" operator in Java because the logical (<<) and arithmetic left-shift (<<<) operations are identical.Next TopicFinal Object in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India