Signed vs unsigned shiftsuggest change
In Java, all number primitives are signed. For example, an int always represent values from [-2^31 - 1, 2^31], keeping the first bit to sign the value - 1 for negative value, 0 for positive.
Basic shift operators
<< are signed operators. They will conserve the sign of the value.
But it is common for programmers to use numbers to store unsigned values. For an int, it means shifting the range to [0, 2^32 - 1], to have twice as much value as with a signed int.
For those power users, the bit for sign as no meaning. That’s why Java added
>>>, a left-shift operator, disregarding that sign bit.
initial value: 4 ( 100) signed left-shift: 4 << 1 8 ( 1000) signed right-shift: 4 >> 1 2 ( 10) unsigned right-shift: 4 >>> 1 2 ( 10) initial value: -4 ( 11111111111111111111111111111100) signed left-shift: -4 << 1 -8 ( 11111111111111111111111111111000) signed right-shift: -4 >> 1 -2 ( 11111111111111111111111111111110) unsigned right-shift: -4 >>> 1 2147483646 ( 1111111111111111111111111111110)
Why is there no
This comes from the intended definition of right-shift. As it fills the emptied places on the left, there are no decision to take regarding the bit of sign. As a consequence, there is no need for 2 different operators.
See this question for a more detailled answer.