How does Java handle integer underflows and overflows?
Leading on from that, how would you check/test that this is occurring?
I think you should use something like this and it is called Upcasting:
public int multiplyBy2(int x) throws ArithmeticException {
long result = 2 * (long) x;
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
throw new ArithmeticException("Integer overflow");
}
return (int) result;
}
You can read further here: Detect or prevent integer overflow
It is quite reliable source.