Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift

Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift:
Java Operators are basically divided into six types,

  • Arithmetic Operators
  • Relational Operators
  • Assignment Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise Operators

In this article, We are going to cover Bitwise Operators. We might face some questions in interviews regarding Bitwise operators. So lets us understand what are bitwise operators with examples.

There are 3 types of Bitwise Operators,

  • Left Shift
  • Right Shift
  • Unsigned Right Shift

Before going ahead, Let us understand what these operators do,

Left Shift Operator:

  • Left shift Operator is declared as <<
  • Left shift operator performs the operation of Multiplication
  • The sign of the the integer, Positive or negative impacts the result of left shift operator
  • Example:
    • 2 << 5
    • Output will be 64. (2^0 * 2^1*…2^5)

Right Shift Operator:

  • Right shift operator is declared as >>
  • Right shift operator performs the operation of Division
  • The sign of the integer, Positive or negative impacts the result of Right Shift Operator
  • Example:
    • 2 >> 5
    • Output: 0, (5 is divided by 2)

Unsigned Right Shift Operator:

  • Unsigned Right Shift Operator is declared as >>>
  • Irrespective of sign, It shifts the bits to 0.
  • Example: -14 >>> 2
    • This is include 2 zero’s (>>>2 — we are requesting it to shift 2 bits) to the left, followed by the value

Once we go through the example, We will be able to understand this clearly.

Output:

op1

Now let us see how this output works,

First we are getting the binary value of Both +7 and -7

7 << 2: Left shift is for multiplication,
so,

7^0 = 7
7^1=7
7^2=14
Actual value is 28 and Binary value is 11100 –> Left Shift Operator Output.

Now for the Second Output,
Right Shift Operator is for division,

7 >> 2: Right Shift for Division,

2 Divided by 7, Not divisible so the value is 1. –> Right Shift Operator Output

Now the Unsigned Right Shift Operator,

7 >> 2 and 7>>>2 are always same, except 2 Zero’s are added to the left of the output. 
-7 >>> 2:
Binary value of -7: 11111111111111111111111111111001, Now we shift 2 Zero’s to the left,
Output is,
00111111111111111111111111111110.

If we use, -7>>> 3 (3 zero’s to the left) Output will be,
00011111111111111111111111111111

One thought on “Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift

Leave a Reply

Your email address will not be published. Required fields are marked *