Because 1
is an int
, not a long
, and the conversion to long
doesn't happen until after the assignment statement. Java will notice that the left hand argument is an int
and not a long
, and will round the right hand value accordingly.
From the JLS:
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.
The behavior will be as expected if the left hand argument is declared with 1L
, as below:
public class BitShifting {
public static void main(String... args) {
long foo = -1L << 23;
long bar = -1L << 55;
System.out.println(foo);
System.out.println(bar);
}
}
Output:
-8388608
-36028797018963968
-1L << 55
and-1L >>> -1
for interest.