If the outer range value cannot be stored in int, shouldnt it be retaining the last value - 1073741824 ?
No, it's storing the result of the final operation, following the overflow rules listed in the JLS on each operation.
If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.
It's not that the result "defaults" to 0 - it's just that one of the operations ended up overflowing so that the last 32 bits were all 0. All multiplications after that would also result in 0.
You can see that if you add diagnostics to each step:
public class Test {
public static void main(String[] args) {
calculatePower(4, 16);
}
public static int calculatePower(int x, int y) {
int result = 1;
for (int i = 0; i < y; i++) {
System.out.printf("%d * %d = %d%n", result, x, result * x);
result = result * x;
}
return result;
}
}
I've simplified your loop at the same time, which means you don't need the base case condition beforehand. Note that neither your original code nor my version handles negative powers - for production code, you should check that and throw an exception.
Output:
1 * 4 = 4
4 * 4 = 16
16 * 4 = 64
64 * 4 = 256
256 * 4 = 1024
1024 * 4 = 4096
4096 * 4 = 16384
16384 * 4 = 65536
65536 * 4 = 262144
262144 * 4 = 1048576
1048576 * 4 = 4194304
4194304 * 4 = 16777216
16777216 * 4 = 67108864
67108864 * 4 = 268435456
268435456 * 4 = 1073741824
1073741824 * 4 = 0
If you raise it to a greater power, e.g. 20, you'll see lines of "0 * 4 = 0" at the end.