Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between operator >> and operator >>> in java?

Tags:

java

bit-shift

I used to use the >> operator for right shifting. Now I've just replaced it with >>> and found the same result. So I can't figure out whether these two are fundamentally equal or not.

like image 753
Md. Arafat Al Mahmud Avatar asked Jul 07 '12 13:07

Md. Arafat Al Mahmud


People also ask

What do you mean by >>> operator in Java?

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?

&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true. so it continues till the end to check atleast one condition to become true.

What is the difference between and &&?

It is a binary AND Operator and copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100. Whereas && is a logical AND operator and operates on boolean operands. If both the operands are true, then the condition becomes true otherwise it is false.


2 Answers

>> is arithmetic (signed) right-shift, >>> is logical (unsigned) right-shift, as described in the Java tutorial. Try them on a negative value, and you will see a difference.

like image 141
Oliver Charlesworth Avatar answered Oct 19 '22 12:10

Oliver Charlesworth


The first operator sign-extends the value, shifting in a copy of the sign bit; the second one always shifts in a zero.

The reason for this is to emulate unsigned integers for the purpose of doing bit operations, partially compensating for the lack of unsigned integral types in Java.

like image 35
Sergey Kalinichenko Avatar answered Oct 19 '22 12:10

Sergey Kalinichenko