21. Computing the quotient of the arguments and result overflow
Let’s start with two simple computations, as follows:
-4/-1 = 4, 4/-1 = -4
This is a very simple use case that works as expected. Now, let’s keep the divisor as -1
, and let’s change the dividend to Integer.MIN_VALUE
(-2,147,483,648):
int x = Integer.MIN_VALUE;
int quotient = x/-1; // -2,147,483,648
This time, the result is not correct. The int
domain was overflowed because of |Integer.MIN_VALUE| > |Integer.MAX_VALUE|
. It should be the positive 2,147,483,648, which doesn’t fit in the int
domain. However, changing the x
type from int
to long
will solve the problem:
long x = Integer.MIN_VALUE;
long quotient = x/-1; // 2,147,483,648
But the problem will reappear if, instead of Integer.MIN_VALUE
, there is Long.MIN_VALUE
:
long y = Long.MIN_VALUE; // -9,223,372,036,854,775,808
long quotient = y/-1; // -9,223,372,036,854,775,808
Starting with JDK 18, the Math...