This is not a Spring problem, it is a common Java problem. Java does not have an overflow problem like C, but it wraps around an integer.
@Test
public void demoIntegerWrapp(){
int value = Integer.MAX_VALUE;
value += 1;
assertEquals(Integer.MIN_VALUE, value);
}
Therefore, it is best to think that you can use long to calculate and check if the result is in the interger range, otherwise throw an exception.
public int overflowSaveAdd(int summand1, int summand2) {
long sum = ((long) summand1) + ((long) summand2);
if (sum < Integer.MIN_VALUE ) || (sum > Integer.MAX_VALUE) {
throw new RuntimeException(sum + " is too big for integer");
} else {
return (int) sum;
}
}
Ralph source
share