Why do the following two operations yield different results in Java for x = 31
or 32
but the same results for x=3
?
int
According to the documentation Math.pow
will promote both of its arguments to double and return double. Obviously when the returned result is double and you cast it to int you'll get only the highest 32 bits and the rest will be truncated - hence you always get the (int) Math.pow(2,x);
value. When you do bitshift you always work with ints and hence an overflow occurs.