Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: clarified that the product is always representable as long

...

Code Block
bgColor#ccccff
int a, b, result;
long temp = (long) a * (long)b;
if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) {
  throw new ArithmeticException("Not in range"); // Overflow
}
result = (int) temp; // Value within range, safe to downcast

Even though a and b are sign extended as a result of casting to long, their product is guaranteed to fit in a variable of type long.

Division

Although Java throws a java.lang.ArithmeticException for division by zero, the same issue as with C/C++ manifests, while dividing the Integer.MIN_VALUE by -1. It produces Integer.MIN_VALUE unexpectedly (as the result is -(Integer.MIN_VALUE) = Integer.MAX_VALUE + 1)).

...