Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there two Right Shift operators and only a single Left Shift operator in Java?

Tags:

java

operators

I am new to java, and came to know that there are two Right Shift operators in java >> and >>>, but only one left shift operator <<. Why is it so?

like image 805
sum2000 Avatar asked Dec 19 '11 13:12

sum2000


People also ask

What is the need to have two right shift operators in Java?

Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.

What is the difference between >> and >>> in Java?

Difference between >> and >>> operator. Both >> and >>> are used to shift the bits towards the right. The difference is that the >> preserve the sign bit while the operator >>> does not preserve the sign bit. To preserve the sign bit, you need to add 0 in the MSB.

What is the difference between Left Shift and Right shift operator?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.

How Left Shift and Right Shift works in Java?

The left shift operator moves all bits by a given number of bits to the left. The right shift operator moves all bits by a given number of bits to the right. It is the same as the signed right shift, but the vacant leftmost position is filled with 0 instead of the sign bit.


1 Answers

Because logical and arithmetic left-shift operations are identical (from wikipedia).

  • Arithmetic shift

RightLeft

  • Logical shift

RightLeft

Notice what happens to sign bit (left-most bit) in both left shifts.

like image 134
bezmax Avatar answered Nov 15 '22 00:11

bezmax