I have problem with shift operator in Java.I have used following code and not unable to understand how this program generates this output.So please guide me how this program generates this output.
public class Operator {
public static void main(String[] args) {
// TODO Auto-generated method stub
int s = 8;
s = s >>-63;
System.out.println("value of i=" + s);
}
}
Output: value of i=4
From the JLS, section 15.19 (Shift Operators):
If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.
Now -63 & 0x1f == 1
, So this is actually a shift by 1 to the right, hence the answer of 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With