Java only uses the portion of the right-hand operand that applies (5 bits if it's an int, 6 bits if it's a long).
For example, -2 in binary is 1111...110 (imagine a string of 1's where those ellipses are). If we're shifting an int, Java only takes the 5 right-most bits, or 11110, which is 30 in binary. So,
13 >> -2 13 >> 30
are identical statements.
There's a Javaranch article on this topic at here. Here's the pertinent portion:
Well, in Java, ints are "signed" variables (they can be positive or negative), so this is a legal line of code:
byte b = 13; b = (byte)(b >> -6);
So now the question is, what does that do? Does it shift left instead of right? Does it give an error? Actually, it does neither. When performing a shift, only a portion of the right hand operand is used. If you're shifting an int, you'll use only the right-most 5 bits of the shift value. That means that the amount you shift by will always fall within the range of 0 and 31. If you're shifting a long, you'll use only the right-most 6 bits of the shift value. In that case, your shift distance falls within 0 and 63. Let's see how that works with our last example:
-6 in binary is 11111010
We're shifting an int (remember that anything smaller than an int is promoted to an int) so we use only the right-most 5 bits of that value. Therefore, we're shifting by 26 (11010 in binary is 26 in decimal). So, our previous line equates to this:
b = (byte)(b >> 26);
Of course, if we shift 13 to the right by 26 positions, we've managed to push all of the real data off the table and replaced it with zeros. So, in the end, we have b equal to 0. [ August 19, 2005: Message edited by: Ryan Kade ]