Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...


By using the BigInteger class there is no chance to overflow (see section on BigInteger class) but the performance is degraded so it should be used only on really large operations
\\\\






Subtraction


Care must be taken in subtraction operations as well as these can overflow as well.

...

Code Block
bgColor#ccccff
int a,b,result;

long temp = (long)a-(long)b;
if(long < Integer.MIN_VALUE || long > Integer.MAX_VALUE)
throw ArithmeticException;
else
result = (int) temp;

...









Multiplication


This noncompliant code example, can result in a signed integer overflow during the multiplication of the signed operands a and b. If this behaviour is unanticipated, the resulting value may lead to undefined behaviour

...

Code Block
bgColor#FFcccc
int a,b,result
//do stuff
result = a*b;//May result in overflow

...









Compliant Code Example

Since in this platform the size of type long (64 bits) is twice the size of type int (32 bits) we should perform the multiplication in terms of long and if the product is in the integer range we downcast the result to int

...

Code Block
bgColor#FFcccc
int a,b,result
result = a/b;

...








Compliant Code Example


 

Code Block
bgColor#ccccff
if(a == Integer.MIN_VALUE && b == -1)
throw ArithmeticException;//May be Integer.MIN_VALUE again????
else
result = a/b;//safe operation

...