** This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details **

The problem

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

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — the following for the answer, according to support sorting votes — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Answer 1 (450 votes supported) :

>> is arithmetic moving right, >>> is logic moving right.

In arithmetic shifts, the sign bits are extended to preserve the symbolic nature of the number.

For example: using 8 bits to represent -2 would be 11111110 (because the most significant bits have a negative weight). Use arithmetic shift >> to move it one bit to the right, and you get 11111111 or -1. However, a logical right shift does not care whether the value is likely to represent a signed number. It just moves everything to the right and fills in zeros from the left. Moving -2 one bit to the right using a logical shift yields 01111111.

Answer 2 (107 votes in favor) :

>>> Unsigned shift; It will insert 0. >> is signed and will extend the sign bit.

The shift operators include left shift <<, signed right shift >> and unsigned right shift >>>.

The result of n>>s is that the signed n shifts s bits to the right.


   System.out.println(Integer.toBinaryString(-1));
    // prints "11111111111111111111111111111111"
    System.out.println(Integer.toBinaryString(-1 >> 16));
    // prints "11111111111111111111111111111111"
    System.out.println(Integer.toBinaryString(-1 >>> 16));
    // prints "1111111111111111"
Copy the code

More clearly:

System.out.println(Integer.toBinaryString(121));
// prints "1111001"
System.out.println(Integer.toBinaryString(121 >> 1));
// prints "111100"
System.out.println(Integer.toBinaryString(121 >>> 1));
// prints "111100"
Copy the code

Since it is positive, both signed and unsigned shifts will add 0 to the leftmost bit.

Answer 3 (50 votes in favour) :

They all move right, but >>> move right for unsigned

From the document:

The unsigned right-shift operator “>>>” shifts an unsigned to the leftmost position, and the leftmost position after “>>” depends on the sign bit.