Javatpoint Logo
Javatpoint Logo

Shift Operators in Java

In 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:

  1. Signed Left Shift Operator (<<)
  2. Signed Right Shift Operator (>>)
  3. Unsigned Right Shift Operator (>>>)

Note: Java does not support the unsigned left shift operator (<<< ).

Signed Left Shift Operator

The 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.

Shift Operators in Java

Assume that the statement is as follows:

x<<4, let y be 4

Shift Operators in Java

Let's implement the above logic in a Java program.

LeftShift.java

Output:

The value is: 80

Signed Right Shift Operator

The 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.

Shift Operators in Java

Assume that the statement is as follows:

x>>4, let y be 4

Shift Operators in Java

Let's implement the above logic in a Java program.

RightShift.java

Output:

The right shifted value is : 5

Unsigned Right Shift Operator

The 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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA