I came across the following program and it behaving in unexpected manner.
public class ShiftProgram
{
public static void main(String[] args)
{
int i = 0;
while(-1 << i != 0)
i++;
System.out.println(i);
}
}
If we think about this program output, when it reaches 32 while loop condition should return false and terminate and it should print 32.
If you ran this program, it does not print anything but goes into an infinite loop. Any idea whats going on? Thank you in advance.
Have you tried printing out
(-1 << i)in the loop to see what’s going wrong? If you do, you’ll see that it goes:According to the language specification:
… so the result will always remain negative.
That document also tells you that:
So if you use a shift of
32, that’s interpreted as a shift of32 & 0x1f, which is0.-1shifted by0is still just-1, not0.